繁体   English   中英

列表到嵌套字典的字典

[英]Dictionary of lists to nested dictionary

我有以下字典{44: [0, 1, 0, 3, 6]} dict1 = {44: {0:0, 1:1, 2:0, 3:3, 4:6}} {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)

你能帮助我吗? 提前致谢。

您可以使用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}}

使用一个使用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}}
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}}

为什么您当前的实现不起作用:

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

为了解决这个问题,你需要idict1[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提供

暂无
暂无

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

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