簡體   English   中英

python遍歷元組列表並創建字典列表

[英]python looping through list of tuples and creating list of dictionary

我正在遍歷此元組列表,並嘗試使其成為包含兩個鍵值對的字典,其中一對是“單詞”:“數據”和“計數”:12

在循環中,當我打印(my_dict)時,它會正確打印我想要的內容,但是當打印final_list時,它給了我一個字典列表,其中所有四個條目都是{word:“ javascript”,count:20}

 my_list = [("data", 12), ("sql", 13), ("python", 4), ("javascript", 20)]

    # make into [{word:"data", count:12},
    #            {word:"sql", count:13},
    #            {word:"python", count:4}...etc]

final_list = []
my_dict = {}

for s in my_list:

    my_dict["word"] = s[0]
    my_dict["count"] = s[1]
    # print(my_dict)
    final_list.append(my_dict)

print(final_list)

當我在循環內創建my_dict時,它可以工作,但是我想知道為什么這是hapeninng。

您正在嘗試建立一個包含許多詞典的列表,您當前的代碼會創建1個字典並將其扔入列表中。 您希望列表中的每個元素都是獨立詞典,它們並不完全相同。 最簡單的解決方法是在for循環的每一遍中將您的字典聲明為新字典:

final_list = []
#my_dict = {} not here

for s in my_list:
    my_dict = {} # here instead!
    my_dict["word"] = s[0]
    my_dict["count"] = s[1]
    # print(my_dict)
    final_list.append(my_dict)

print(final_list)

這將使代碼按您期望的方式運行

OUTPUT:

[{'word': 'data', 'count': 12}, {'word': 'sql', 'count': 13}, {'word': 'python', 'count': 4}, {'word': 'javascript', 'count': 20}]
my_list = [("data", 12), ("sql", 13), ("python", 4), ("javascript", 20)]

    # make into [{word:"data", count:12},
    #            {word:"sql", count:13},
    #            {word:"python", count:4}...etc]

final_list = []
my_dict = {}

for s in my_list:

    my_dict["word"] = s[0]
    my_dict["count"] = s[1]
    # print(my_dict)
    final_list.append(my_dict.copy())

print(final_list)

產量

[{'count': 12, 'word': 'data'}, {'count': 13, 'word': 'sql'}, {'count': 4, 'word': 'python'}, {'count': 20, 'word': 'javascript'}]

這是因為您在列表之外聲明了my_dict 每次修改它時,您都在修改相同的字典-並將相同的字典四次放入列表。

解決方案是在循環的每次迭代中聲明一個新的dict 您只需將my_dict = {}放入循環中即可:

final_list = []
for s in my_list:
    my_dict = {}
    my_dict["word"] = s[0]
    my_dict["count"] = s[1]
    # print(my_dict)
    final_list.append(my_dict)

您還可以通過完全消除幫助程序變量並進行列表理解來簡化代碼:

final_list = [{'word': s[0], 'count': s[1]} for s in my_list]

您需要在迭代時添加新字典:

my_list = [("data", 12), ("sql", 13), ("python", 4), ("javascript", 20)]

result = []
for word, count in my_list:
    result.append({"word": word, "count": count})

print(result)
# [{'word': 'data', 'count': 12}, {'word': 'sql', 'count': 13}, {'word': 'python', 'count': 4}, {'word': 'javascript', 'count': 20}]

您還可以使用列表理解:

result = [{"word": word, "count": count} for word, count in my_list]

我想知道為什么這是hapeninng。

正如我在評論中提到的,在循環之前分配一次dict對象,並在每次迭代中使用相同的對象。 結果,您獲得了對相同字典的引用列表。

您可以使用簡單的列表理解替換以下代碼:

my_list = [("data", 12), ("sql", 13), ("python", 4), ("javascript", 20)]

final_list = [{"word": key, "count": value} for key, value in my_list]

輸出:

[{'word': 'data', 'count': 12}, {'word': 'sql', 'count': 13}, {'word': 'python', 'count': 4}, {'word': 'javascript', 'count': 20}]

看這部分...

for s in my_list:

my_dict["word"] = s[0]
my_dict["count"] = s[1]

每次循環瀏覽時,您都在更改字典中的值。 因此,有意義的是,字典的最終值將成為元組列表中的最后一項。 我希望這是有道理的。

現在查看循環的最后一行...

for s in my_list:

    my_dict["word"] = s[0]
    my_dict["count"] = s[1]
    # print(my_dict)
    final_list.append(my_dict)

每次將字典追加到列表時,都不會創建字典的新副本。 您正在創建對字典的新引用。 因此,列表中的所有字典都指向每次循環都會更改的內存中的同一空間。 做你想做的事情,你有選擇...

將字典的副本追加到列表中。 這會在內存中創建一個具有字典所具有值的新空間,並將其追加到列表中。 這樣,當您更新my_dict時,先前的值已存儲在其他位置。

for s in my_list:

    my_dict["word"] = s[0]
    my_dict["count"] = s[1]
    # print(my_dict)
    final_list.append(my_dict.copy())

您可以在每次循環訪問值時在內存中創建一個新字典。

for s in my_list:
my_dict = {} # here instead!
my_dict["word"] = s[0]
my_dict["count"] = s[1]
# print(my_dict)
final_list.append(my_dict)

還有其他一些更好的方法,但是希望這可以幫助您解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM