-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']

4 Answers4

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']]
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']
summea
  • 7,390
  • 4
  • 32
  • 48
0

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

Osama Adel
  • 176
  • 1
  • 10
  • 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?"](//stackoverflow.com/help/how-to-answer) – John Conde Feb 17 '21 at 01:16
-1

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

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