问题描述
list = [("a",1),("b",2),("a",3),("c",1)]
我想将此元组列表转换成字典。
输出:
{'a': [1,3,2],'b': [2,1],'c': [1]}
我的代码:
list_a = [("a",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,1,'b': [1,'c': [1,1]}
解决方法
list_a = [("a",1),("b",2),("a",3),("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]}
,
下面是一个选项。美观且可读
阅读下面代码中的注释
list = [("a",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]]
,
还有其他的builin库可以帮助您解决问题,但与此同时,我们可以使用本机逻辑来解决它。
list_ = [('a',('b',('a',('c',1)]
result = {}
for i in list_:
result[i[0]] = (result.get(i[0]) or []) + [i[1]]
print(result) # {'a': [1,'c': [1]}