Mustafa Rahman
Mustafa Rahman

Reputation: 29

How can i extract a dictionary from a nested dictionary?

suppose i have a nested dictionary

x = {'town1': {'thames': 'moderate', 'bourton': 'low'},
     'town2': {'river cam': 'high'},
     'town3': {'dickler': 'moderate', 'mil': 'severe'}}

I want to extract the town name and the risk level (high, moderate, low, or severe)

desired output:

y = {'town1': ['moderate', 'low'],
     'town2': ['high'],
     'town3': ['moderate', 'severe']}

This is my code:

d = []
for k,v in x.items():
    d.append((k,(v)))
y=[]
for i in range(len(d)):
    for k,v in d[i][1].items():
        y.append((d[i][0],v))
print(y)

Upvotes: 2

Views: 85

Answers (3)

res = {k: list(v.values()) for k, v in x.items()}

Upvotes: 1

igorkf
igorkf

Reputation: 3565

One way:

y = {a[0]: list(a[1].values()) for a in x.items()}

Results will be:

{
    'town1': ['moderate', 'low'],
    'town2': ['high'],
    'town3': ['moderate', 'severe']
}

Upvotes: 1

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use list comprehension inside a dictionary comprehension:

x = {'town1': {'thames': 'moderate', 'bourton': 'low'}, 'town2': {'river cam': 'high'}, 'town3': {'dickler': 'moderate', 'mil': 'severe'}}
y = {k: [v for k, v in v.items()] for k, v in x.items()}
print(y)
# {'town1': ['moderate', 'low'], 'town2': ['high'], 'town3': ['moderate', 'severe']}

Upvotes: 2

Related Questions