基于python中的公共值将列表列表转换为字典

2024-04-25 05:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个列表,如下所示:

a = [['John', 24, 'teacher'],['Mary',23,'clerk'],['Vinny', 21, 'teacher'], ['Laura',32, 'clerk']]

其想法是根据他们的职业创建一个dict,如下所示:

b = {'teacher': {'John_24': 'true', 'Vinny_21' 'true'},
     'clerk' : {'Mary_23': 'true', 'Laura_32' 'true'}}

实现这一目标的最佳方法是什么?你知道吗


Tags: 方法true目标列表johndictmaryteacher
2条回答

正如其他人所说,你可以只使用列表而不是字典。你知道吗

有一种方法可以实现这一点:

a = [
    ['John', 24, 'teacher'],
    ['Mary', 23, 'clerk'],
    ['Vinny', 21, 'teacher'],
    ['Laura', 32, 'clerk'],
]

b = {}
for name, age, occupation in a:
    b.setdefault(occupation, []).append('{}_{}'.format(name, age))

print b  # {'clerk': ['Mary_23', 'Laura_32'], 'teacher': ['John_24', 'Vinny_21']}

您可以使用defaultdict:

a = [['John', 24, 'teacher'],['Mary',23,'clerk'],['Vinny', 21, 'teacher'], ['Laura',32, 'clerk']]


from collections import defaultdict

dct = defaultdict(defaultdict)


for name, age, occ in a:
    dct[occ][name + "_" + age] = "true"

输出:

from pprint import pprint as pp

pp(dict(dct))
 {'clerk': defaultdict(None, {'Laura_32': 'true', 'Mary_23': 'true'}),
'teacher': defaultdict(None, {'John_24': 'true', 'Vinny_21': 'true'})}

尽管你也可以把每个名字添加到一个列表中:

from collections import defaultdict

dct = defaultdict(list)

for name, _, occ in a:
    dct[occ].append(name + "_" + age) 

这会给你:

 defaultdict(<class 'list'>, {'clerk': ['Mary_23', 'Laura_32'], 'teacher': ['John_24', 'Vinny_21']})

如果以后要使用年龄,还可以将其单独存储:

from collections import defaultdict

dct = defaultdict(list)


for name, age, occ in a:
    dct[occ].append([name, age])

这会给你:

defaultdict(<class 'list'>,
            {'clerk': [['Mary', 23], ['Laura', 32]],
             'teacher': [['John', 24], ['Vinny', 21]]})

使用python3,您可以使用:

for *nm_age, occ in a:
    dct[occ].append(nm_age)

相关问题 更多 >