I'm trying to create a function that will go through a nested dictionary and add the value of a key to a nested value, and create a new nested key-value pair. So for instance this input:
current_dict = {1: {'int1': 11}, 2: {'int1': 12}, 3: {'int1': 13}, 4: {'int1': 14},
5: {'int1': 15}}
would look like this output:
new_dict = {1: {'int1': 11, 'int2': 12}, 2: {'int1': 12, 'int2', 14},
3: {'int1': 13, 'int2', 16}, 4: {'int1': 14, 'int2': 18}, 5: {'int1': 15, 'int2', 20}}
I was working with a non-nested dictionary with something similar to add key-value pairs to create a new value using this:
int_dict = {1: 11, 2: 12, 3: 13, 4: 14, 5: 15}
new_dict2 = {}
def func2(k, v):
new_k = k + v
return new_k
for k, v in integer_dictionary.items():
new_dict2[k] = func2(k, v)
and returns this:
{1: 12, 2: 14, 3: 16, 4: 18, 5: 20}
Ideally I would like to build out this function to be able to handle nested dictionaries as described above, but I'm not sure how to handle iterating through the nested elements.
You can use a dictionary comprehension:
current_dict = {1: {'int1': 11}, 2: {'int1': 12}, 3: {'int1': 13}, 4: {'int1': 14}, 5: {'int1': 15}}
new_dict = {a:{**b, 'int2':b['int1']+a} for a, b in current_dict.items()}
Output:
{1: {'int1': 11, 'int2': 12}, 2: {'int1': 12, 'int2': 14}, 3: {'int1': 13, 'int2': 16}, 4: {'int1': 14, 'int2': 18}, 5: {'int1': 15, 'int2': 20}}
Edit: without a comprehension:
def funct2(k, v):
return {**v, 'int2':v['int1']+k}
for a, b in current_dict.items():
current_dict[a] = funct2(a, b)
Output:
{1: {'int1': 11, 'int2': 12}, 2: {'int1': 12, 'int2': 14}, 3: {'int1': 13, 'int2': 16}, 4: {'int1': 14, 'int2': 18}, 5: {'int1': 15, 'int2': 20}}
A function that can do that could look like:
def add_new_value_from_key_value(a_dict, key_add_from, key_to_add):
a_dict = a_dict.copy()
for k, v in a_dict.items():
v[key_to_add] = k + v[key_add_from]
return a_dict
current_dict = {1: {'int1': 11}, 2: {'int1': 12}, 3: {'int1': 13},
4: {'int1': 14}, 5: {'int1': 15}
}
new_dict = {
1: {'int1': 11, 'int2': 12},
2: {'int1': 12, 'int2': 14},
3: {'int1': 13, 'int2': 16},
4: {'int1': 14, 'int2': 18},
5: {'int1': 15, 'int2': 20}
}
print(add_new_value_from_key_value(current_dict, 'int1', 'int2'))
assert new_dict == add_new_value_from_key_value(current_dict, 'int1', 'int2')
{
1: {'int1': 11, 'int2': 12},
2: {'int1': 12, 'int2': 14},
3: {'int1': 13, 'int2': 16},
4: {'int1': 14, 'int2': 18},
5: {'int1': 15, 'int2': 20}
}
This should work:
current_dict = {1: {'int1': 11}, 2: {'int1': 12}, 3: {'int1': 13}, 4: {'int1': 14}, 5: {'int1': 15}}
new_dict = current_dict.copy()
for k, v in new_dict.iteritems():
v['int2'] = v['int1'] + k
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.