Search code examples
pythondictionarydictionary-comprehension

Python Dictionary Key and Values Question


  • 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'}}

Solution

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