我有以下字典{44: [0, 1, 0, 3, 6]}
,需要将其转换为dict1 = {44: {0:0, 1:1, 2:0, 3:3, 4:6}}
,但当前的for循环不起作用:
maxnumbers = 5 #this is how many values are within the list
for i in list(range(maxnumbers)):
for k in list(dict1.keys()):
for g in dict1[k]:
newdict[i] = g
print(num4)
你能帮我吗?预先感谢。
答案 0 :(得分:13)
您可以对enumerate
使用字典理解:
d = {44: [0, 1, 0, 3, 6]}
{k:dict(enumerate(v)) for k,v in d.items()}
# {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
答案 1 :(得分:5)
使用简单的嵌套字典理解,该理解使用enumerate
:
d = {44: [0, 1, 0, 3, 6]}
print({k: {i: x for i, x in enumerate(v)} for k, v in d.items()})
# {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
答案 2 :(得分:2)
a = {44: [0, 1, 0, 3, 6]}
a= {i:{j:a[i][j] for i in a for j in range(len(a[i]))}}
print(a)
输出
{44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}}
答案 3 :(得分:1)
您当前的实现为何无效:
for i in list(range(maxnumbers)):
for k in list(dict1.keys()):
for g in dict1[k]:
# this will iterate over all of the values in
# d1[k] and the i: v pair will be overwritten by
# the last value
newdict[i] = g
分步骤来看,这看起来像:
# for value in [0, 1, 0, 3, 6]: Just take this set of values as an example
# first, value is 0, and say we are on i = 1, in the outer for loop
newdict[1] = 0
# Then it will progress to value = 1, but i has not changed
# which overwrites the previous value
newdict[1] = 1
# continues until that set of values is complete
要解决此问题,您需要i
和dict1[k]
的值一起增加。这可以通过zip
完成:
for index, value in zip(range(maxnumbers), dict1[k]):
newdict[index] = value
此外,如果您需要同时访问键和值,请使用dict.items()
:
for k, values in dict1.items():
# then you can use zip on the values
for idx, value in zip(range(maxnumbers), values):
但是,enumerate
函数已经简化了此操作:
for k, values in dict1.items():
for idx, value in enumerate(values):
# rest of loop
这更加健壮,因为您不必提前发现maxnumbers
。
要在您一直使用的传统for循环中执行此操作:
new_dict = {}
for k, v in dict1.items():
sub_d = {} # create a new sub_dictionary
for i, x in enumerate(v):
sub_d[i] = x
# assign that new sub_d as an element in new_dict
# when the inner for loop completes
new_dict[k] = sub_d
或更紧凑地说:
d = {44: [0, 1, 0, 3, 6]}
new_d = {}
for k, v in d.items():
new_d[k] = dict(enumerate(v))
dict
构造函数将以2元素tuples
的可迭代对象作为参数,enumerate
提供了