Understanding conditional vocabulary

So I'm wondering if anyone can help me with this problem that I have.

Suppose I have a dictionary:

d = {1: {2: 3}, 4: 5}

I want to create a dictionary of any dictionaries contained:

wanted_result = {2: 3}

I am trying to do this:

e = {inner_key: d[key][inner_key] for key in d.keys() for inner_key in d[key].keys() if isinstance(d[key], dict)}

However, this forces me to receive a message that ints do not have the keys that I know, but I thought that my conditional exception would say 4 from my example from inclusion in understanding.

+3
source share
6 answers

My first idea was something like this:

d = {1: {2: 3}, 4: 5, 6: {7: 8}}
generator = (x.items() for x in d.itervalues() if type(x) == dict)
s = dict(sum( generator, list() )) 
# s = {2: 3, 7: 8}

But, to avoid creating a sum()large temporary list of everyone items(), you can use itertools.chain and iteritems()instead:

# chain "concatenates" iterables
from itertools import chain
d = {1: {2: 3}, 4: 5, 6: {7: 8}}
s = dict(chain( *(x.iteritems() for x in d.itervalues() if type(x) == dict) ))
# s = {2: 3, 7: 8}

. , , - .


dict, d.values(), isinstance type. . .

+1
d = {1: {2: 3}, 4: 5, 6: {7: 8}}
s = {k: v for elem in d.values() if type(elem) is dict for k, v in elem.items()}
>> {2: 3, 7: 8}
+10

In this case, I would recommend you the for-loop method and update:

d = {1: {2: 3}, 4: 5, 6: {7: 8}}
inner_dicts = {}
for val in d.values():
    if type(val) is dict:
        inner_dicts.update(val)
print inner_dicts
# {2: 3, 7: 8}
+2
source

The following list comprehension will return every value that is a dict:

>>> d = {1: {2: 3}, 4: 5}
>>> [d[i] for i in d.keys() if isinstance(d[i],dict)]
[{2: 3}]
+1
source
d = {1: {2: 3}, 4: 5,'j':{7:8}}
e={y:d[x][y] for x in d if isinstance(d[x],dict) for y in d[x]}
print(e)

{2: 3, 7: 8}
+1
source

Another way to use lambda

(lambda x: {k:v for x in d.values() if type(x) == dict for k,v in x.items()})(d)

0
source

All Articles