1

I have a list where it consists of a list inside a list. The inner list contains two items with inner_list[0] is an identifier/key and inner_list[1] is the corresponding value. I would like to put them into a dictionary where values that shares the same key will be appended to the same key.

An example:

list = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'], ['Sept', 'Joey'],..['key', 'value']]

The outcome I was looking for:

Jan = ['Jim', 'Chris']
Feb = ['Maggie']
Sept = ['Joey']

Any ideas I can do this elegantly in Python?

2
  • for the record, the inner type is effectively a tuple (and ut should be a tuple if it is up to you) Commented Jun 11, 2013 at 5:33
  • 1
    use collections.defaultdict Commented Jun 11, 2013 at 5:39

2 Answers 2

6

You can use collections.defaultdict here:

>>> from collections import defaultdict
>>> lis = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'], ['Sept', 'Joey'],['key', 'value']]
>>> dic = defaultdict(list)
>>> for k, v in lis:
...     dic[k].append(v)

>>> dic['Jan']
['Jim', 'Chris']
>>> dic['Feb']
['Maggie']
>>> dic['Sept']
['Joey']
Sign up to request clarification or add additional context in comments.

Comments

0

you could use setdefault, so:

lis = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'], 
       ['Sept', 'Joey'], ['key', 'value']]
dic = {}
for key, val in lis:
    dic.setdefault(key, []).append(val)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.