[英]Insert values of list of lists in a dictionary declared with keys
I have this list of lists:我有这个列表列表:
x = [['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11'],
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11'],
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11']]
And I have a declared dictionary like:我有一个声明的字典,例如:
d = {"x": None, "y": None, "z": None, "t": None,
"a": None, "s": None, "m": None, "n": None,
"u": None, "v": None, "b": None}
What I want to get is a list or dictionry such as:我想要得到的是一个列表或字典,例如:
result = [{"x": x1,
"y": x2,
"z": x3,
"t": x4,
"a": x5,
"s": x6,
"m": x7,
"n": x8,
"u": x9,
"v": x10,
"b": x11}, {"x": x1,
"y": x2,
"z": x3,
"t": x4,
"a": x5,
"s": x6,
"m": x7,
"n": x8,
"u": x9,
"v": x10,
"b": x11}...]
And so on.等等。 One dictionary inside the list per each element inside x (list of lists).
x (列表列表)中的每个元素在列表中都有一个字典。
Try:尝试:
result = [dict(zip(d, subl)) for subl in x]
print(result)
Prints:印刷:
[
{
"x": "x1",
"y": "x2",
"z": "x3",
"t": "x4",
"a": "x5",
"s": "x6",
"m": "x7",
"n": "x8",
"u": "x9",
"v": "x10",
"b": "x11",
},
...
The dict(zip(d, subl))
will iterate over keys of dictionary d
and values of sublists of x
at the same time and creates new dictionary (with keys from d
and values from sublist). dict(zip(d, subl))
将同时迭代字典d
的键和x
的子列表的值,并创建新字典(来自d
的键和来自子列表的值)。 This works for Python 3.7+ as the dictionary keeps insertion order.这适用于 Python 3.7+,因为字典保持插入顺序。
From Python 3.7, dictionary order is guaranteed to be insertion order.从 Python 3.7 开始,字典顺序保证为插入顺序。 So my answer does only make sense if you're using Python >=3.7.
所以我的回答只有在你使用 Python >=3.7 时才有意义。
Here is how you can do it:您可以这样做:
result = [dict(zip(d, lst)) for lst in x]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.