Home > Blockchain >  How can I concat the values of Dictionaries Within A Dictionary in Python
How can I concat the values of Dictionaries Within A Dictionary in Python

Time:03-25

I have a dictionary in the following format:

data = {
    'Bob': {
        'age': 12,
        'weight': 150,
        'eye_color': 'blue'
    },
    'Jim': {
        'favorite_food': 'cherries',
        'sport': 'baseball',
        'hobby': 'running'
    },
    'Tom': {
        'strength': 'average',
        'endurance': 'high',
        'heart_rate': 'low'
    }
}

What is the most pythonic way to concatenate all of the dictionaries within dict into a new dictionary so that I would end up with something like the following:

new_dict = {
    'age': 12,
    'weight': 150,
    'eye_color': 'blue',
    'favorite_food': 'cherries',
    'sport': 'baseball',
    'hobby': 'running',
    'strength': 'average',
    'endurance': 'high',
    'heart_rate': 'low'
}

CodePudding user response:

You can use functools.reduce() to build up the result, unioning one dictionary at a time:

from functools import reduce

data = {
 'Bob' : { 'age': 12, 'weight': 150, 'eye_color': 'blue' },
 'Jim' : { 'favorite_food': 'cherries', 'sport': 'baseball', 'hobby': 'running' },
 'Tom' : { 'strength': 'average', 'endurance': 'high', 'hear_rate': 'low' }
}

# Can use x | y or operator.or_ instead of dict(**x, **y) if on Python 3.9 or higher.
# The latter is from a suggestion by Mad Physicist.
result = reduce(lambda x, y: dict(**x, **y), data.values(), {})

print(result)

This outputs:

{'age': 12, 'weight': 150, 'eye_color': 'blue', 'favorite_food': 'cherries',
'sport': 'baseball', 'hobby': 'running', 'strength': 'average',
'endurance': 'high', 'hear_rate': 'low'}

CodePudding user response:

One option is to use a dictionary comprehension with a nested generator expression:

new_dict = {k: v for d in data.values() for k, v in d.items()}
  • Related