Chad Chad - 7 months ago 26
Python Question

Python print key in all dictionaries

If I have a file that contains these dictionaries:

{
"dict1" : {
"data1" : "a",
"data2" : "b",
"data3" : "c",
"data4" : "d",
"data5" : "e"
},
"dict2" : {
"data1" : "f",
"data2" : "g",
"data3" : "h",
"data4" : "i",
"data5" : "j"
}


How would I go about accessing every dictionary key "data3". Such that the output would be:

c, h


Because there are multiple dictionaries inside the file I won't know the names. Is there anyway to iterate over them to pull out those keys?

Answer
>>> ', '.join(subdict['data3'] for subdict in maindict.values())
'c, h'

Explanation:

Your data is a dictionary maindict, where the keys are 'dict1' and 'dict2'.

>>> for key in maindict.keys():
...     print key
dict1
dict2

We're not interested in the keys, but want the values (which are actually two more dictionaries):

>>> for value in maindict.values():
...     print value
{"data1" : "a",
 "data2" : "b",
 "data3" : "c",
 "data4" : "d",
 "data5" : "e"}
{"data1" : "f",
 "data2" : "g",
 "data3" : "h",
 "data4" : "i",
 "data5" : "j"}

To get the value in the sub-dictionary corresponding to key 'data3':

>>> for subdict in maindict.values():
...     print subdict['data3']
c
h

You said you wanted a comma separated result. str.join allows you to join a sequence of strings using other characters as a separator:

>>> ', '.join(['William', 'Shatner', 'Speaks', 'Like', 'This'])
'William, Shatner, Speaks, Like, This'

The final piece of the puzzle is that we can generate sequences on the fly using a generator expression to create a generator:

>>> results = (subdict['data3'] for subdict in maindict.values())
>>> results
<generator object <genexpr> at 0x03115710>

You can pass a generator anywhere a sequence is expected:

>>> list(results)
['c', 'h']

So, we use a generator expression with str.join:

>>> ', '.join(subdict['data3'] for subdict in maindict.values())
'c, h'
Comments