【问题标题】:converts this list of tuples into a dictionary将此元组列表转换为字典
【发布时间】:2020-12-08 08:00:27
【问题描述】:

我有一个元组列表。

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

我想把这个元组列表转换成字典。

输出:

{'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]}

【问题讨论】:

标签: python python-3.x dictionary tuples


【解决方案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]}

【讨论】:

  • 我没有抄袭你……老实说!! :) 哈哈它离我很近。
【解决方案2】:

下面是一个选项。好看又好读

阅读下面代码中的cmets

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

#create dictionary
dic = {}

#iterate each item in the list
for itm in list:
    #check if first item in the tuple is in the keys of the dictionary
    if itm[0] in dic.keys():
        #if so append the list
        dic[itm[0]].append(itm[1])
    else:
        #if not create new key, value pair (value is a list as enclosed with [])
        dic[itm[0]] = [itm[1]]        
        

【讨论】:

  • 这与接受的答案有何本质不同?这似乎只是重命名变量,并使用效率较低的itm[0] in dic.keys() 而不是itm[0] in dic 检查。
  • 根本没有。它几乎是一个副本。但是我在答案发布之前就开始写了。
【解决方案3】:

还有其他内置库可以帮助您解决问题,但同时我们可以使用本机逻辑来解决它。

list_ = [('a', 1), ('b', 2), ('a', 3), ('b', 1), ('a', 2), ('c', 1)]
result = {}
for i in list_:
    result[i[0]] = (result.get(i[0]) or []) + [i[1]]

print(result)  # {'a': [1, 3, 2], 'b': [2, 1], 'c': [1]}

【讨论】:

  • dict.setdefault 为此而存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2010-09-20
  • 2017-06-07
相关资源
最近更新 更多