有一本字典:
data = {'Common': {'height': 165, 'weight': 70, 'measure': ['cm', 'kg']},
'Man': 'handsome',
'Woman': {'feature': 'pretty', 'weight': 50},
'Dog': {'feature': 'barks', 'height': 10, 'weight': 20}}
只想将字典键转换为大写。
尝试了以下代码:
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()] = d1
else:
d[k.upper()] = v
print(d)
...这会产生带有不必要的键和高度和重量合理化的输出,如下所示:
{'COMMON': {'HEIGHT': 10, 'WEIGHT': 20, 'MEASURE': ['cm', 'kg'], 'FEATURE': 'barks'},
'MAN': 'handsome',
'WOMAN': {'HEIGHT': 10, 'WEIGHT': 20, 'MEASURE': ['cm', 'kg'], 'FEATURE': 'barks'},
'DOG': {'HEIGHT': 10, 'WEIGHT': 20, 'MEASURE': ['cm', 'kg'], 'FEATURE': 'barks'}}
我的预期输出是:
{'COMMON': {'HEIGHT': 165, 'WEIGHT': 70, 'MEASURE': ['cm', 'kg']},
'MAN': 'handsome',
'WOMAN': {'FEATURE': 'pretty', 'WEIGHT': 50},
'DOG': {'FEATURE': 'barks', 'HEIGHT': 10, 'WEIGHT': 20}}
我哪里错了?
正确的字典理解是什么样的{{i.upper(): j} if isinstance(j, dict) else {k.upper(): v} for k, v in data.items() for i, j in v.items()}?
湖上湖
牧羊人nacy
相关分类