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: 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With