Insert values of list of lists in a dictionary declared with keys

Question:

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).

Solutions in python3 are correct,however in python2 would be even better.

Asked By: Jordi Lazo

||

Answers:

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). This works for Python 3.7+ as the dictionary keeps insertion order.


EDIT: I’d recommend to change d from dict to list:

from collections import OrderedDict

d = ["x", "y", "z", "t", "a", "s", "m", "n", "u", "v", "b"]
result = [OrderedDict(zip(d, subl)) for subl in x]
print(result)

OR:

Use collections.OrderedDict:

from collections import OrderedDict

d = OrderedDict(
    [
        ("x", None),
        ("y", None),
        ("z", None),
        ("t", None),
        ("a", None),
        ("s", None),
        ("m", None),
        ("n", None),
        ("u", None),
        ("v", None),
        ("b", None),
    ]
)

result = [OrderedDict(zip(d, subl)) for subl in x]
print(result)
Answered By: Andrej Kesely

From Python 3.7, dictionary order is guaranteed to be insertion order. So my answer does only make sense if you’re using Python >=3.7.

Here is how you can do it:

result = [dict(zip(d, lst)) for lst in x]
Answered By: Riccardo Bucco