簡體   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