Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python - how do I convert items to dict?

I have following list of items (key-value pairs):

items = [('A', 1), ('B', 1), ('B', 2), ('C', 3)]

What I want to get:

{
  'A' : 1,
  'B' : [1,2]
  'C' : 3
}

My naive solution:

res = {}
for (k,v) in items:
     if k in res:
         res[k].append(v)
     else:
         res[k] = [v]

I'm looking for some optimised more pythonic solution, anyone?

like image 995
mnowotka Avatar asked Oct 18 '25 14:10

mnowotka


1 Answers

Use could use defaultdict here.

from collections import defaultdict

res = defaultdict(list)
for (k,v) in items:
    res[k].append(v)
# Use as dict(res)

EDIT:

This is using groupby, but please note, the above is far cleaner and neater to the eyes:

>>> data = [('A', 1), ('B', 1), ('B', 2), ('C', 3)]
>>> dict([(key,list(v[1] for v in group)) for (key,group) in groupby(data, lambda x: x[0])])
{'A': [1], 'C': [3], 'B': [1, 2]}

Downside: Every element is a list. Change lists to generators as needed.


To convert all single item lists to individual items:

>>> res = # Array of tuples, not dict
>>> res = [(key,(value[0] if len(value) == 1 else value)) for key,value in res]
>>> res
[('A', 1), ('B', [1, 2]), ('C', 3)]
like image 77
UltraInstinct Avatar answered Oct 20 '25 04:10

UltraInstinct



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!