2 回答
TA贡献2003条经验 获得超2个赞
您可以这样做,dict使用所需的密钥复制到其他:
data = {'Common': {'height': 165, 'weight': 70, 'measure': ['cm', 'kg']},
'Man': 'handsome',
'Woman': {'feature': 'pretty', 'weight': 50},
'Dog': {'feature': 'barks', 'height': 10, 'weight': 20}}
data2 = {}
for k in data.keys():
data2[k.upper()] = data[k]
更新:如果您不仅要更改级别 1 上的键,则应使用递归函数:
data = {'Common': {'height': 165, 'weight': 70, 'measure': ['cm', 'kg']},
'Man': 'handsome',
'Woman': {'feature': 'pretty', 'weight': 50},
'Dog': {'feature': 'barks', 'height': 10, 'weight': 20}}
def keys_to_upper(dict1):
dict2 = {}
for k in dict1.keys():
if isinstance(dict1[k], dict):
dict2[k.upper()] = keys_to_upper(dict1[k])
else:
dict2[k.upper()] = dict1[k]
return dict2
d2 = keys_to_upper(data)
TA贡献1862条经验 获得超7个赞
您的代码的问题是,d1如果值是字典,您正在重新分配。您可以使用以下方法解决此问题copy.deepcopy():
代码:
from copy import deepcopy
d = {}
d1 = {}
for k, v in data.items():
if isinstance(v, dict):
for i, j in v.items():
d1[i.upper()] = j
d[k.upper()] = deepcopy(d1)
else:
d[k.upper()] = v
输出:
>>> d
{'COMMON': {'HEIGHT': 165, 'WEIGHT': 70, 'MEASURE': ['cm', 'kg']},
'MAN': 'handsome',
'WOMAN': {'FEATURE': 'pretty', 'WEIGHT': 50},
'DOG': {'FEATURE': 'barks', 'HEIGHT': 10, 'WEIGHT': 20}}
或者,作为字典理解:
>>> {k.upper(): {i.upper(): j for i, j in v.items()} if isinstance(v, dict) else v for k, v in data.items()}
{'COMMON': {'HEIGHT': 165, 'WEIGHT': 70, 'MEASURE': ['cm', 'kg']},
'MAN': 'handsome',
'WOMAN': {'FEATURE': 'pretty', 'WEIGHT': 50},
'DOG': {'FEATURE': 'barks', 'HEIGHT': 10, 'WEIGHT': 20}}
添加回答
举报