简体   繁体   English

使用元组中的键和元组列表中的值创建字典

[英]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'.我正在尝试使用来自 x 的键和来自元组“用户”列表的值创建一个字典。 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.此外,我从元组 x 和元组“用户”列表中硬编码索引值来访问元组值。 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?如何使代码动态化,以便将新键添加到用户的 x 和值时,它会添加到我的输出中? I have checked the web to find an answer but couldn't find anything similar to my question.我检查了网络以找到答案,但找不到与我的问题类似的任何内容。 This is my first StackOverflow question.这是我的第一个 StackOverflow 问题。 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)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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