Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading