Search code examples
pythonlistdictionaryvariablesassign

How to assign multiple variables based on dicts in a list (The list is sorted different each run)


Say I have this data:

data = [{'name': "Name 1", 'value': None}, {'name': "Name 2", 'value': None}, {'name': "Name 3", 'value': None}]

How can I assign three variables based on this data, given that each time the code is run, the dicts may be shuffled. Meaning that "Name 1" could potentially be found in either index 0, 1 or 2.

I did try this:

for x in data:
  if x['name'] == 'Name 1':
      a = x['value']
      continue
  if x['name'] == 'Name 2':
      b = x['value']
      continue
  if x['name'] == 'Name 3':
      c = x['value']
      continue

But I find this rather ugly. Is there a better, more Pythonic way?

a, b, c = ??

Solution

  • You can transform the data list to temporary dictionary where keys are names. For example:

    data = [
        {"name": "Name 1", "value": None},
        {"name": "Name 2", "value": None},
        {"name": "Name 3", "value": None},
    ]
    
    tmp = {d["name"]: d["value"] for d in data}
    a, b, c = tmp.get("Name 1"), tmp.get("Name 2"), tmp.get("Name 3")
    
    print(a, b, c)
    

    Prints:

    None None None