Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 887
Vinodh Avatar asked Jun 29 '11 14:06

Vinodh


2 Answers

Index the list then the dict.

print L[1]['d'] 
like image 78
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 17:09

Ignacio Vazquez-Abrams


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] 
like image 42
Artsiom Rudzenka Avatar answered Sep 20 '22 17:09

Artsiom Rudzenka