Home > other >  Insert values of list of lists in a dictionary declared with keys
Insert values of list of lists in a dictionary declared with keys

Time:08-31

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.

CodePudding user response:

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.

CodePudding user response:

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]
  • Related