我有一个字典,其值是一个列表:
dict ={10: ['jhon', 'abc', 'wa@gmail.com'], 12: ['raghav', 'awdaw', 'raghavpatnecha15@gmail.com']}
现在我这样访问它们:
dict[10][0]
但它让我感到困惑,因为我不知道我的列表中索引0的特定键是什么。
为此,我有另一个列表,它可以帮助我索引i的内容。
['Manager Name', 'Owner Name', 'Email']
所以知道这可以轻松访问我的字典的值。就像我想要使用的那样:dict[10]['Manager Name']
而不是dict[10][0]
这是否可以在Python中实现。因为我尝试了Map two list in to dictionary的引用但是如何将字典值映射到列表
答案 0 :(得分:3)
是的,有可能。只需将字典重组为嵌套字典:
d_input = {10: ['jhon', 'abc', 'wa@gmail.com'],
12: ['raghav', 'awdaw', 'raghavpatnecha15@gmail.com']}
d = {k: {'Manager Name': a, 'Owner Name': b, 'Email': c} \
for k, (a, b, c) in d_input.items()}
结果:
{10: {'Email': 'wa@gmail.com', 'Manager Name': 'jhon', 'Owner Name': 'abc'},
12: {'Email': 'raghavpatnecha15@gmail.com', 'Manager Name': 'raghav', 'Owner Name': 'awdaw'}}
zip
的可扩展版本:
cats = ['Manager Name', 'Owner Name', 'Email']
d = {k: dict(zip(cats, v)) for k, v in d_input.items()}
答案 1 :(得分:3)
这是classes的明确用例。
python不是拥有代表['jhon', 'abc', 'wa@gmail.com']
等公司的列表,而是让您可以将其建模为类:
class Company:
def __init__(self, manager_name, owner_name, email):
self.manager_name = manager_name
self.owner_name = owner_name
self.email = email
companies = {10: Company('jhon', 'abc', 'wa@gmail.com'),
12: Company('raghav', 'awdaw', 'raghavpatnecha15@gmail.com'}
这为您提供了比列表更好的界面,因为您可以按名称而不是索引访问属性:
>>> comp = Company('jhon', 'abc', 'wa@gmail.com')
>>> comp.manager_name
'jhon'
>>> comp.owner_name
'abc'
>>> comp.email
'wa@gmail.com'
如果您懒惰并且不想手动定义Company
类,则可以使用collections.namedtuple
来减少必须编写的代码量:
from collections import namedtuple
Company = namedtuple('Company', 'manager_name owner_name email')
您还可以轻松地将列表的字典转换为Company
个实例的字典:
companies = {10: ['jhon', 'abc', 'wa@gmail.com'],
12: ['raghav', 'awdaw', 'raghavpatnecha15@gmail.com']}
comps = {num: Company(*comp) for num, comp in companies.items()}
# result:
# {10: Company(manager_name='jhon', owner_name='abc', email='wa@gmail.com'),
# 12: Company(manager_name='raghav', owner_name='awdaw', email='raghavpatnecha15@gmail.com')}
答案 2 :(得分:2)
如果您的“属性”始终是['Manager Name', 'Owner Name', 'Email']
,则应考虑使用namedpuples或Python 3.7的新dataclass
。
以下是使用namedtuples的示例:
from collections import namedtuple
Company = namedtuple('Company', ['manager', 'owner', 'email'])
comp = Company('jhon', 'abc', 'wa@gmail.com')
print(comp.manager, comp.owner, comp.email)
结果为jhon abc wa@gmail.com
答案 3 :(得分:1)
您应该使用named tuples。
您的代码可能如下所示:
from collections import namedtuple
Company = namedtuple('Company', 'ManagerName OwnerName Email')
c1 = Company('jhon', 'abc', 'wa@gmail.com')
c2 = Company('raghav', 'awdaw', 'raghavpatnecha15@gmail.com')
companies = {10: c1, 12: c2}
companies[10].Email
答案 4 :(得分:1)
如果您不想更改字典,可以使用另一个字典将索引映射到相应的值。
>>> d = {10: ['jhon', 'abc', 'wa@gmail.com'], 12: ['raghav', 'awdaw', 'raghavpatnecha15@gmail.com']}
>>> mapper = {'Manager Name': 0, 'Owner Name': 1, 'Email': 2}
>>> d[10][mapper['Manager Name']]
'jhon'
>>> d[12][mapper['Email']]
'raghavpatnecha15@gmail.com'