I have a nested dictionary which contains a list and would like to do the following:
- Update the dictionary name to
A
,B
,C
,D
instead ofdict1
,dict2
- Remove
key3
and it's values from the dictionary
Here is the current input example:
{'dict_1': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3'], 'key3': ['value1', 'value2', 'value3']} 'dict_2': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3'], 'key3': ['value1', 'value2', 'value3']}}
Desired output:
{'A': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3']} 'B': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3']}}
I have tried using ascii lowercase to change letter but this did not work. To remove key3 I tried using del and pop which did not work either. Please could someone let me know where I am going wrong?
CodePudding user response:
Here is the solution involving ascii values
and .pop()
.
Try this :
nested_dict = {
'dict_1': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3'], 'key3': ['value1', 'value2', 'value3']},
'dict_2': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3'], 'key3': ['value1', 'value2', 'value3']}}
key_name = 'A'
new_nested_dict = {}
for k, v in nested_dict.items():
v.pop('key3', None)
new_nested_dict[key_name] = v
key_name = chr(ord(key_name) 1)
print(new_nested_dict)
Output:
{'A': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3']}, 'B': {'key1': ['data1', 'data2', 'data3'], 'key2': ['1', '2', '3']}}