本文介绍了将此元组列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组列表。

list = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]

我想将此元组列表转换成字典。

I want to converts this list of tuples into a dictionary.

输出:

{'a': [1, 3, 2], 'b': [2, 1], 'c': [1]}

我的代码:

list_a = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]
new_dict = {}
value = []
for i in range(len(list_a)):
    key = list_a[i][0]

    value.append(list_a[i][1])

    new_dict[key] = value
print(new_dict)

但是,我的输出如下:

{'a': [1, 2, 3, 1, 2, 1], 'b': [1, 2, 3, 1, 2, 1], 'c': [1, 2, 3, 1, 2, 1]}


推荐答案

list_a = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]
new_dict = {}

for item in list_a:
    # checking the item[0] which gives the first element
    # of a tuple which is there in the key element of
    # of the new_dict
    if item[0] in new_dict:
        new_dict[item[0]].append(item[1])
    else:
        # add a new data for the new key
        # which we get by item[1] from the tuple
        new_dict[item[0]] = [item[1]]
print(new_dict)

输出

{'a': [1, 3, 2], 'b': [2, 1], 'c': [1]}

这篇关于将此元组列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 18:12