-1

So I know this: Python list of dictionaries search

answers the first part of my question.

However, my issue is as such: I want to actually update that searched for dictionary directly, not simply retrieve it.

More specifically, I have a list of dictionaries. The dictionaries each have a "list" key whose value is another list. I want to update that list once I find the dictionary.

The structure for each dictionary is as such: {"name": "whatever", "display":"whoever", "list": [x, y, z]}

So an example list would be:

[
    {"name": "whatever", "display":"whoever", "list": [x, y, z]},
    {"name": "whatever2", "display":"whoever2", "list": [x2, y2, z2]},
    {"name": "whatever3", "display":"whoever3", "list": [x3, y3, z3]}
]

I want to retrieve, say, the dictionary with name "whatever2" and add a2 to the "list".

What is the best way to do this?

"Best" can be however you weigh "python-ness" / "performance" / code clarity etc.

Community
  • 1
  • 1
axb252
  • 1

1 Answers1

1
L = [
    {"name": "whatever", "display":"whoever", "list": [x, y, z]},
    {"name": "whatever2", "display":"whoever2", "list": [x2, y2, z2]},
    {"name": "whatever3", "display":"whoever3", "list": [x3, y3, z3]}
]

for d in L:
    if d['name'] != 'whatever2': continue
    d['list'].append('a2')
    break  # unless you could have multiple dictionaries in your list with the same name
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241