简体   繁体   中英

Create dictionary with keys from tuple and values from list of tuple

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", "jhon@company.com"),
         (3, "mike", "mike@company.com"),
         (4, "sam", "sam@company.com")]

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

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

list_of_dicts = [{'id': 2, 'name': 'jhon', 'email': 'jhon@company.com'}, {'id': 3, 'name': 'mike', 'email': 'mike@company.com'}, {'id': 4, 'name': 'sam', 'email': 'same@company.com'}]

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.

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': ['jhon@company.com', 'mike@company.com', 'sam@company.com']}

For the second:

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

output:

[{'id': 2, 'name': 'jhon', 'email': 'jhon@company.com'},
 {'id': 3, 'name': 'mike', 'email': 'mike@company.com'},
 {'id': 4, 'name': 'sam', 'email': 'sam@company.com'}]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM