简体   繁体   中英

converts this list of tuples into a dictionary

I have a list of tuples.

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

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

Output:

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

My code:

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)

However, my output is as follows:

{'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)

OUTPUT

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

One option is below. Nice and readable

Read the comments in the code below

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]]        
        

There are other builin libraries that might help you solve the problem but for the mean time we can solve it using native logic.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM