简体   繁体   English

将字典元素合并到列表列表中

[英]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. 任何帮助深表感谢。

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. 请注意,由于不对字典进行排序,因此子列表的排序可能会有所不同。

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]

You can use list comprehension to put the items in a list. 您可以使用list comprehension将项目放在列表中。 Also, use get() method on dict so that it does not throw key error if the key is not present in the other dict. 另外,对dict使用get()方法,以便如果另一个dict中不存在键,则它不会引发键错误。

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

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()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM