Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary within dictionary in Python 3

I'm seeking to make a function addproperty(property_str, property_dict, old_dict = None) where I you need as arguments a string, one dictionary and one optional dictionary. The function needs to return a new dictionary where the corresponding values are added to the optional dictionary.

For instance. If I enter:

capitals_dict = {'USA': 'Washington', 'Russia': 'Moscow', 'Japan': 'Tokyo'}

The function addproperty('capital', capitals_dict) needs to return the following dictionary

{'USA': {'capital': 'Washington'}, 'Russia': {'capital': 'Moscow'}, 'Japan': {'capital': 'Tokyo'}}

I also need to be able to expand such dictionary to add new details to those countries when I enter that dictionary in the optional parameter.

For instance:

old_dict = {'USA': {'capital': 'Washington'}, 'Russia': {'capital': 'Moscow'}, 'Japan': 'capital': 'Tokyo'}}
demonym_dict = {'USA': 'American', 'Russia': 'Russian', 'Japan': 'Japanese'}

Then addproperty('demonym', demonym_dict, old_dict) needs to return:

{'USA': {'capital': 'Washington', 'demonym': 'American'}, 'Russia': {'capital': 'Moscow', 'demonym': 'Russian'}, 'Japan': {'capital': 'Tokyo', 'demonym': 'Japanese'}}

How should I start here?

like image 677
Denny Nuyts Avatar asked Mar 24 '23 04:03

Denny Nuyts


2 Answers

def addproperty(property_str, property_dict, old_dict=None):
    result = old_dict if old_dict is not None else {}
    for k, v in property_dict.items():
        result.setdefault(k, {})[property_str] = v
    return result

For example:

>>> capitals_dict = {'USA': 'Washington', 'Russia': 'Moscow', 'Japan': 'Tokyo'}
>>> result = addproperty('capital', capitals_dict)
>>> result
{'Japan': {'capital': 'Tokyo'}, 'Russia': {'capital': 'Moscow'}, 'USA': {'capital': 'Washington'}}
>>> demonym_dict = {'USA': 'American', 'Russia': 'Russian', 'Japan': 'Japanese'}
>>> addproperty('demonym', demonym_dict, result)
{'Japan': {'demonym': 'Japanese', 'capital': 'Tokyo'}, 'Russia': {'demonym': 'Russian', 'capital': 'Moscow'}, 'USA': {'demonym': 'American', 'capital': 'Washington'}}

Note that this will modify old_dict if it is provided. If this is a problem import the copy module and replace the first line in the function with the following:

result = copy.deepcopy(old_dict) if old_dict is not None else {}
like image 198
Andrew Clark Avatar answered Mar 26 '23 18:03

Andrew Clark


My crazy one-line solution :)

def addproperty(property_str, property_dict, old_dict = None):
    return {k: (lambda k, v: old_dict[k] if old_dict != None else { property_str: v})(k,v) for k, v in property_dict.items()}

Returns new dictionary.

like image 39
Arthur Galuza Avatar answered Mar 26 '23 17:03

Arthur Galuza