Electric
Electric

Reputation: 537

Combining dictionary elements into a list of list

I have two dictionaries with contents:

dct1 = {'NL': 7,'MC': 9, 'PG': 8}
dct2 = {'NL': 2,'MC': 10,'PG': 6}

You could say these represents scores from a game where the letters are names and the numbers are scores. The difference between the two dictionaries are the numbers in which they are calculated based on criteria.

Now i want to combine the contents from the dictionary into a list of list. I'm going to provide just a rough idea of my code. Basically what i did then was turning the contents in the two dictionaries into a list of list where:

L1 = [['NL',7],['MC',9],['PG',8]]
L2 = [['NL',2],['MC',10],['PG',6]]

The code for turning them into a list of list:

L1 = []
for i, occurrences in dct1.items():
    L1.append([i,occurrences])
L2 = []
for j, occurrences in dct2.items():
    L2.append([j,occurrences])

and once i print both list, i get as what I've written above.

But now, instead of having two different list, i want to combine both of them into a single list where my output is:

L3 = [['NL',7,2],['MC',9,10],['PG',8,6]]

Basically the single list does not have to repeat the letters twice and just adding the second digit. Any help is much appreciated.

Upvotes: 0

Views: 124

Answers (4)

Vishvajit Pathak
Vishvajit Pathak

Reputation: 3721

Assuming you are using python 2.7.x

For understanding

L3 = []
for key, value in dct1.iteritems():
    L3.append([key, value, dct2[key])

OR

Short and Sweet using List comprehension :

L3 =  [[key, value, dct2[key]] for key, value in dct1.iteritems()]

Upvotes: 0

Charul
Charul

Reputation: 450

You can use list comprehension to put the items in a list. Also, use get() method on dict so that it does not throw key error if the key is not present in the other dict.

>>> [(key, val, dct1.get(key)) for key, val in dct2.items()]
[('NL', 2, 7), ('PG', 6, None), ('MC', 10, 9)]

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19743

As key is same in both dictionary:

>>> dct1 = {'NL': 7,'MC': 9, 'PG': 8}

>>> dct2 = {'NL': 2,'MC': 10,'PG': 6}
>>> L3 = []
>>> for key in dct1:
...     L3.append([key, dct1[key], dct2[key]])
... 
>>> L3
[['NL', 7, 2], ['PG', 8, 6], ['MC', 9, 10]

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78554

A list comprehension should do:

lst =  [[k, v, dct2[k]] for k, v in dct1.items()]
print lst
# [['NL', 7, 2], ['PG', 8, 6], ['MC', 9, 10]]

Note that ordering of the sublists may vary, since dictionaries are not ordered.

Upvotes: 9

Related Questions