skip to Main Content

I have the following lists:

list1 = ["Hulk", "Flash", "Tesla"]
list2 = ["green", "23", "thunder"]
list3 = ["Marvel", "DC_comics", "0.0"]

and I would like to create a dictionary like this one:

{
    "eo:dict": [
        {"name": "Hulk", "color": green, "company": Marvel},
        {"name": "Flash", "color": red, "company": DC_comics},
        {"name": "Tesla", "color": thunder, "company": 0.0},
    ]
}

that has to be appended in a specific position within a json file I’m creating.

I tried in this way:

keys = ["name", "company", "colours"]
eo_dict = dict(zip(keys, name,company, color))

but I got the error "_ValueError: dictionary update sequence element #0 has length 3; 2 is required_"

Could anybody give me some hints?

2

Answers


  1. You can use this code to get the expected output:

    list1 = ['Hulk', 'Flash', 'Tesla']
    list2 = ['green', '23', 'thunder']
    list3 = ['Marvel', 'DC_comics', '0.0']
    keys = ['name', 'color', 'company']
    
    out = list(dict(zip(keys, values)) for values in zip(list1, list2, list3))
    

    Output:

    >>> out
    [{'name': 'Hulk', 'color': 'green', 'company': 'Marvel'},
     {'name': 'Flash', 'color': '23', 'company': 'DC_comics'},
     {'name': 'Tesla', 'color': 'thunder', 'company': '0.0'}]
    

    To export as JSON:

    import json
    
    jd = json.dumps([{'eo:dict': out}], indent=4)
    print(jd)
    
    # Output
    [
        {
            "eo:dict": [
                {
                    "name": "Hulk",
                    "color": "green",
                    "company": "Marvel"
                },
                {
                    "name": "Flash",
                    "color": "23",
                    "company": "DC_comics"
                },
                {
                    "name": "Tesla",
                    "color": "thunder",
                    "company": "0.0"
                }
            ]
        }
    ]
    
    Login or Signup to reply.
  2. You should try this one,

    keys = ["name", "age", "location"]
    values = ["John", 28, "New York"]
    
    my_dict = {k:v for k, v in zip(keys, values)}
    
    print(my_dict)
    

    The output is like

    {‘name’: ‘John’, ‘age’: 28, ‘location’: ‘New York’}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search