我有一个字典,如:
a={'name':'jhonson','profession':'doctor','location':'new york'}
现在,我想创建一个新的字典,其键为'doc_*counter'
。诸如此类:
new_dict={'doc_1':{'name':'jhonson'},'doc_2':{'profession':'doctor'},'doc_3':{'location':'new york'}}
我的表现:
count=0
new_dict={}
for k,v in a.items():
count+=1
new_dict['doc'+str(count)][k]=v
答案 0 :(得分:0)
您可以使用enumerate():
Python枚举()
enumerate()方法向可迭代对象添加计数器并返回它(枚举对象)。
a={'name':'jhonson','profession':'doctor','location':'new york'}
new_dict = {}
for idx, key in enumerate(a.keys()):
new_dict['doc_' + str(idx)] = {key: a[key]}
print (new_dict)
输出:
{'doc_0': {'name': 'jhonson'}, 'doc_1': {'profession': 'doctor'}, 'doc_2': {'location': 'new york'}}
或仅使用列表理解:
a={'name':'jhonson','profession':'doctor','location':'new york'}
new_dict = {'doc_' + str(idx): {key: a[key]} for (idx, key) in enumerate(a.keys())}
print (new_dict)
输出:
{'doc_0': {'name': 'jhonson'}, 'doc_1': {'profession': 'doctor'}, 'doc_2': {'location': 'new york'}}
答案 1 :(得分:0)
并添加到前面的答案中。如果您在枚举中使用a.items()
。您可以在字典中解压缩键值对。
a={'name':'jhonson','profession':'doctor','location':'new york'}
new_dict = {}
for idx, (key, value) in enumerate(a.items()):
new_dict['doc' + str(idx)] = {key: value}
print(new_dict)
这将删除对键值{key: a[key]}
的多余查找。