How to access a dictionary key value present inside a list?
PythonPython Problem Overview
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
?
Python Solutions
Solution 1 - Python
Index the list then the dict.
print L[1]['d']
Solution 2 - Python
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:
res.update(line)
res['d']
>>> 4
Otherwise:
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]
Solution 3 - Python
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
mylist[1]['d']
Solution 4 - Python
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]
Solution 5 - Python
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}]
subtitle=[]
for value in list:
subtitle.append(value['text'])