56

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?

2
  • 15
    What's wrong with list[1]['d']?
    – Matt Ball
    Jun 29, 2011 at 14:03
  • how about accessing two keys, is that possible? list[0]['a','b'] @MattBall
    – gmwill934
    Dec 19, 2019 at 8:10

5 Answers 5

53

Index the list then the dict.

print L[1]['d']
0
21

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]
1
  • I didn't downvote, but you are using the anti-pattern funcname = lambda .... Feb 11, 2012 at 16:38
17

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']
1
  • 7
    @raja: No need to thank me, and especially no need to call me Sir! :) Remember to upvote the answers you think are helpful.
    – Rob Cowie
    Jun 29, 2011 at 14:18
5

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]
2
  • 1
    Fix 'if k in in d:' to 'if k in d:' Jun 29, 2011 at 14:14
  • this doesn't work if I'm looking for the value of a particular key in a nested dictionary that's in a list
    – clover
    Jan 19, 2020 at 3:16
4

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'])

Not the answer you're looking for? Browse other questions tagged or ask your own question.