1

I have this list:

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

I want to convert it into a dictionary which looks like:

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

I tried this:

for key, value is list:
    if key in list_dictionary:
        dict(list_dictionary)
    else:
        list_dictionary[key] = value

and the output came:

{'a': 1, 'b': 2, 'c': 1}

What should I do?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Lucifer
  • 51
  • 1
  • 7

3 Answers3

1

The problem is that your value would be covered.You could use defaultdict:

from collections import defaultdict

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

for key, value in l:
    r[key].append(value)

print(r)

This gave me:

defaultdict(<class 'list'>, {'a': [1, 3, 2], 'b': [2, 1], 'c': [1]})
Kevin Mayo
  • 1,089
  • 6
  • 19
1

below

from collections import defaultdict
data = defaultdict(list)
 
lst = [("a", 1), ("b", 2), ("a", 3), ("b", 1), ("a", 2), ("c", 1)]
for entry in lst:
    data[entry[0]].append(entry[1])
print(data)
balderman
  • 22,927
  • 7
  • 34
  • 52
0

My approach is bit different, probably you can checkout this answer too:

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

final = {}
for item in user_list:
    final.update(
        {
            item[0]: [item[1]] + final[item[0]] if final.get(item[0]) else [item[1]]
        }
    )
print(final)

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

CK__
  • 1,252
  • 1
  • 11
  • 25