How to access a dictionary key value present inside a list?

Each Answer to this Q is separated by one/two green lines.

Suppose I have the following list:

list = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]

How do I access a particular value of key say d?

Index the list then the dict.

print L[1]['d']

First of all don’t use ‘list’ as variable name.

If you have simple dictionaries with unique keys then you can do the following(note that new dictionary object with all items from sub-dictionaries will be created):

res  = {}
for line in listOfDicts:
>>> 4


getValues = lambda key,inputData: [subVal[key] for subVal in inputData if key in subVal]
getValues('d', listOfDicts)
>>> [4]

Or very base:

def get_value(listOfDicts, key):
    for subVal in listOfDicts:
        if key in subVal:
            return subVal[key]

You haven’t provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)

One answer is to iterate the list, and attempt to get ‘d’

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]

Another answer is to access the dict directly (by list index), though you have to know that the key is present


If you know which dict in the list has the key you’re looking for, then you already have the solution (as presented by Matt and Ignacio). However, if you don’t know which dict has this key, then you could do this:

def getValueOf(k, L):
    for d in L:
        if k in d:
            return d[k]

To get all the values from a list of dictionaries, use the following code :

list = [{'text': 1, 'b': 2}, {'text': 3, 'd': 4}, {'text': 5, 'f': 6}]
for value in list:

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .