Home > other >  Access value of a given key in a list of dictionaries
Access value of a given key in a list of dictionaries

Time:10-23

Given a list of dictionaries such as:

list_ = [
        { 'name' : 'date',
          'value': '2021-01-01'
        },
        { 'name' : 'length',
          'value': '500'
        },
        { 'name' : 'server',
          'value': 'g.com'
        },

How can I access the value where the key name == length?

I want to avoid iteration if possible, and just be able to check if the key called 'length' exists, and if so, get its value.

CodePudding user response:

With iteration, and using next, you could do:

list_ = [
    {'name': 'date',
     'value': '2021-01-01'
     },
    {'name': 'length',
     'value': '500'
     },
    {'name': 'server',
     'value': 'g.com'
     }
]

res = next(dic["value"] for dic in list_ if dic.get("name", "") == "length")
print(res)

Output

500

As an alternative, if the "names" are unique you could build a dictionary to avoid further iterations on list_, as follows:

lookup = {d["name"] : d["value"] for d in list_}
res = lookup["length"]
print(res)

Output

500

Notice that if you need a second key such as "server", you won't need to iterate, just do:

lookup["server"]  # g.com

CodePudding user response:

It sure is hard to find an element in a list without iterating through it. Thats the first solution I will show:

list(filter(lambda element: element['name'] == 'length', list_))[0]['value']

this will filter through your list only the elements with name 'length', choose the first from that list, then select the 'value' of that element.

Now, if you had a better data structure, you wouldn't have to iterate. In order to create that better data structure, unfortunately, we will have to iterate the list. A list of dicts with "name" and "value" could really just be a single dict where "name" is the key and "value" is the value. To create that dict:

dict_ = {item['name']:item['value'] for item in list_} 

then you can just select 'length'

dict_['length']
  • Related