Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Chad Avatar asked Mar 13 '23 11:03

Chad


2 Answers

>>> ', '.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'
like image 128
Peter Wood Avatar answered Mar 23 '23 05:03

Peter Wood


Assuming you have your dict like this (you forgot a closing }):

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

Just use a generator expression:

>>> i_key = 'data3' # inner key
>>> for value in (dct[o_key][i_key] for o_key in dct if i_key in dct[o_key]):
...     print(value)
h
c

This will only print the data3 value if it exists in the nested dictionary otherwise it is simply skipped.

like image 29
MSeifert Avatar answered Mar 23 '23 06:03

MSeifert