简体   繁体   English

Python - 嵌套字典删除键并更新字典名称

[英]Python - nested dictionary remove key and update dictionary name

I have a nested dictionary which contains a list and would like to do the following:我有一个包含列表的嵌套字典,并希望执行以下操作:

  1. Update the dictionary name to A , B , C , D instead of dict1 , dict2将字典名称更新为A , B , C , D而不是dict1 , dict2
  2. Remove key3 and it's values from the dictionary从字典中删除key3及其值

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.我曾尝试使用 ascii 小写字母来更改字母,但这不起作用。 To remove key3 I tried using del and pop which did not work either.要删除 key3,我尝试使用 del 和 pop 也不起作用。 Please could someone let me know where I am going wrong?请有人让我知道我哪里出错了吗?

Here is the solution involving ascii values and .pop() .这是涉及ascii values.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']}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM