Home > Enterprise >  Create dictionary with keys from tuple and values from list of tuple
Create dictionary with keys from tuple and values from list of tuple

Time:05-25

I am trying to create a dictionary with keys from x and values from a list of tuples 'users'. I need output in two formats: dict of lists & list of dict.

#input
users = [(2, "jhon", "[email protected]"),
         (3, "mike", "[email protected]"),
         (4, "sam", "[email protected]")]

x = ("id", "name", "email")

#expected output:
dict_of_lists = {'id': [2, 3, 4], 'name': ['jhon', 'mike', 'sam'], 'email': ['[email protected]', '[email protected]', '[email protected]']}

list_of_dicts = [{'id': 2, 'name': 'jhon', 'email': '[email protected]'}, {'id': 3, 'name': 'mike', 'email': '[email protected]'}, {'id': 4, 'name': 'sam', 'email': '[email protected]'}]

My code to generate dict of lists:

Dict = {}
def Add(key, value):
  Dict[key] = value
 
ListId=[]
ListName=[]
ListEmail=[]

for i in range(len(users)):
    ListId.append(users[i][0])
    ListName.append(users[i][1])
    ListEmail.append(users[i][2])
      
Add(x[0],ListId)
Add(x[1],ListName)
Add(x[2],ListEmail)
print(Dict)

My code to generate list of dict:

res = []
for i in range(len(users)):
    Dict = {x[0] : users[i][0] , x[1] : users[i][1] , x[2]: users[i][2]}
    res.append(Dict)
print(res)

I am looking for any other efficient solution to this question. Also, I have hardcoded index value from tuple x & list of tuple 'users' to access tuple value. How can I make code dynamic such that when a new key is added to x & value to users, it gets added to my output? I have checked the web to find an answer but couldn't find anything similar to my question. This is my first StackOverflow question. In case you have any suggestions for my question to write or ask in a better way then do let me know.

CodePudding user response:

For the first one:

dict_of_lists = dict(zip(x, map(list, zip(*users))))
# or if tuples are fine
# dict_of_lists = dict(zip(x, zip(*users)))

output:

{'id': [2, 3, 4],
 'name': ['jhon', 'mike', 'sam'],
 'email': ['[email protected]', '[email protected]', '[email protected]']}

For the second:

list_of_dicts = [dict(zip(x,l)) for l in users]

output:

[{'id': 2, 'name': 'jhon', 'email': '[email protected]'},
 {'id': 3, 'name': 'mike', 'email': '[email protected]'},
 {'id': 4, 'name': 'sam', 'email': '[email protected]'}]

CodePudding user response:

Use list comprehension and dict comprehension:

list_of_dicts = [dict(zip(x,u)) for u in users]
dict_of_lists = {k: [u[i] for u in users] for i, k in enumerate(x)}
  • Related