Home > Mobile >  How to write Dictionary from list with Duplicate Keys
How to write Dictionary from list with Duplicate Keys

Time:05-10

Would like to convert list into dictionary, but here I have duplicate keys and it should not be considered in output_dict.

Following is input list and expected dictionary.

input_list = [[1,'a'],[1,'b'],[2,'c'],[2,'d']]

output_dict = {
            1:['a','b'],
            2:['c','d']
          }

Wrote following programme and it gives desired result but somehow feel that it is not standard way of doing things in python. Any other way to write this ?

from pprint import pprint

output_dict = {}
list2 = []
input_list = [[1,'a'],[1,'b'],[2,'c'],[2,'d']]

keys = []
for i in input_list:
    keys.append(i[0])

for key in keys:
    list2 = []
    for i in input_list:
        if key in i:
            list2.append(i[1])
    output_dict[key] = list2


print("\n\n")   
pprint(output_dict)

CodePudding user response:

You can use collections.defaultdict or use dict.setdefault to have shorter code:

input_list = [[1, "a"], [1, "b"], [2, "c"], [2, "d"]]

out = {}
for k, v in input_list:
    out.setdefault(k, []).append(v)

print(out)

Prints:

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

CodePudding user response:

I would suggest using set() to remove the duplicates from the list and then append it into a dictionary!

input_list = list(set(input_list))

  • Related