1
votes
  • I have a list of tuples that I wish to use as values for my new dictionary.
  • I have a list of strings that I wish to use as keys for my new dictionary.
  • However I want to use the capital city as a key for the nested dictionary.
    users = [
        (0, "Bob", "Paris", "password"),
        (1, "Jack", "Berlin", "python"),
        (2, "Jenna", "London" ,"overflow"),
        (3, "Eva", "Stockholm" ,"1234")
    ]
    
    
    office_employees = ["id","Name","key"]

The output I expect is the following:

    {'Paris':{"id":0,"Name":"Bob",key:"password"},'Berlin':{"id":1,"Name":"Jack",key:"python"},"London":{"id":2,"Name":"Jenna",key:"overflow"},"Stockholm":{"id":3,"Name":"Eva",key:"1234"}}

Therefore I used dictionary comprehension. I tried various filtering options but it does not seem to work in any way.

    {item[2]: dict(zip(office_employees, item)) for index, item in enumerate(users)}

The output I receive:

    {'Berlin': {'Name': 'Jack', 'id': 1, 'key': 'Berlin'},
     'London': {'Name': 'Jenna', 'id': 2, 'key': 'London'},
     'Paris': {'Name': 'Bob', 'id': 0, 'key': 'Paris'},
     'Stockholm': {'Name': 'Eva', 'id': 3, 'key': 'Stockholm'}}
4

4 Answers

3
votes

Therefore I used dictionary comprehension.

Don't use dictionary comprehension if it's not convenient.

d = {}
for u in users:
    id_, name, capital, key = u
    d[capital] = {
        'id': id_,
        'Name': name,
        'key': key
    }

It's infinitely more simple this way.

3
votes

Is this what You want? just need to use indexes:

users = [
        (0, "Bob", "Paris", "password"),
        (1, "Jack", "Berlin", "python"),
        (2, "Jenna", "London" ,"overflow"),
        (3, "Eva", "Stockholm" ,"1234")
    ]


office_employees = ["id","Name","key"]

d = {item[2]: dict(zip(office_employees, (item[0], item[1], item[3]))) for item in users}
print(d)

So basically for the zipping You can just use:

dict(zip(office_employees, (item[0], item[1], item[3])))
1
votes

Here is a little ugly way to achieve what you want.

code:

users = [
        (0, "Bob", "Paris", "password"),
        (1, "Jack", "Berlin", "python"),
        (2, "Jenna", "London" ,"overflow"),
        (3, "Eva", "Stockholm" ,"1234")
    ]
office_employees = ["id","Name","key"]
ans = {}
for user in users:
    ans[user[2]]={office_employees[0]:user[0],office_employees[1]:user[1],office_employees[2]:user[3]}
print(ans)

result:

{'Paris': {'id': 0, 'Name': 'Bob', 'key': 'password'}, 'Berlin': {'id': 1, 'Name': 'Jack', 'key': 'python'}, 'London': {'id': 2, 'Name': 'Jenna', 'key': 'overflow'}, 'Stockholm': {'id': 3, 'Name': 'Eva', 'key': '1234'}}
-1
votes

I think you'll need to get the capital city into another array before creating the nested dictionary.

cap_cities = [ user[2] for user in users ]