-3

Trying to learn Python. I have a key in a dict where the value is a list. Is it possible to append a string to all items in the list?

value = {
  "mything": ["pizza", "burger", "tacos"]
}

category = "food-"
print (value["mything"])
# prints ['pizza', 'burger', 'tacos']

What I want to achieve is this output:

print (value["mything"])
# prints ['food-pizza', 'food-burger', 'food-tacos']
2
  • Yes: iterate through the list and concatenate to each. Replace the old string with the new. Where are you stuck with this? Commented Feb 16, 2021 at 20:58
  • value['mything'] = [category + x for x in value['mything']] Commented Feb 16, 2021 at 20:58

4 Answers 4

1

Since you're new, here's a simple loop to get what you need.

for key in iter(value.keys()):
    value[key] = ["food-"+ v for v in value[key]]

But, I would prefer this:

value['mything'] = ['food-'+v for v in value['mything']]
Sign up to request clarification or add additional context in comments.

Comments

0

Here is a simple approach of how this could be done, partly based on your code:

value = {
  "mything": ["pizza", "burger", "tacos"]
}

category = "food-"
results = []
for item in value["mything"]:
    results.append(category + item)

print(results)

Output:

$ python3 example.py
['food-pizza', 'food-burger', 'food-tacos']

Comments

0

print(["food-"+i for i in value["mything"]])

1 Comment

Code dumps do not make for good answers. You should explain how and why this solves their problem. I recommend reading, "How do I write a good answer?"
-1

You could use list comprehension to prepend the category to all items in the list

print ([category+food for food in value["mything"]])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.