Home > Mobile >  Dictionary comprehension python
Dictionary comprehension python

Time:11-22

I have the following dictionary:

cars_info_with_colors = {
    "red": {"audi": [105, 55], "toyota": [105, 66]}, 
    "blue": {"renault": [102, 33], "mercedes": [100, 80]}
}

I want to have the nested dictionary's only and I can do it like that:


removed_colors_dict = {}

for car in cars_info_with_colors:
    cars_info_without_colors.update(cars_info_with_colors[car])

# output:

removed_colors_dict = {
    'audi': [105, 55],
    'toyota': [105, 66],
    'renault': [102, 33],
    'mercedes': [100, 80]
}

I want to do it with dictionary comprehension but i have failed multiply times. I will be really thankful if someone can show me how can I do it, thank you a lot! Have a wonderful day! (sorry for gramma and bad explanations!)

Thats some of the ways I tried to do it:

{k: v for k, v in cars_with_colors.values}
{k: v for k, v in cars_with_colors for v in cars_with_colors.values]

CodePudding user response:

This will work.

cars_info_with_colors = {
    "red": {"audi": [105, 55], "toyota": [105, 66]}, 
    "blue": {"renault": [102, 33], "mercedes": [100, 80]}
}

result = {k2:v2 for k1,v1 in cars_info_with_colors.items() for k2,v2 in v1.items()}
#         k1='red' v1={'audi':[...], ...}        k2 ='audi',v2=[105,55]

print(result)

Since we want the key and value of the dictionary that are the values of the top level (key,value) combo... you need to run another for loop within the comprehension to extract and flatten those values.

output:

{'audi': [105, 55],
 'toyota': [105, 66],
 'renault': [102, 33],
 'mercedes': [100, 80]}
  • Related