python中的列表到字典

2024-06-13 20:31:24 发布

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

我有这种类型的列表,我正试图将其转换为字典,但键在重复,我无法这样做

清单如下:


my_list = [['full name ',
  ' Arthur Schopenhauer',
  'date of birth ',
  ' Friday, February 22, 1788 (232 years ago)',
  'place of birth ',
  ' Gdansk, Pomorskie, Poland',
  'date of death ',
  ' Friday, September 21, 1860 (age: 72 years) ',
  'place of death ',
  ' Frankfurt, Hesse, Germany'],
 ['full name ',
  ' Aristotle',
  'date of birth ',
  ' 384 BC (2403 years ago)',
  'place of birth ',
  ' Halkidiki, Macedonia Central, Greece',
  'date of death ',
  ' 322 BC (age: 62 years) ',
  'place of death ',
  ' Evvoia, Greece Central, Greece']]

我想得到的是:

my_dict = {"full name": ['Arthur Schopenhauer', 'Aristotle'],
 "date of birth": [' Friday, February 22, 1788 (232 years ago)', '384 BC (2403 years ago)'],
 "place of birth": [...],
 "date of death": [...],
 "place of death": [...]}

你能帮我一些建议或意见吗


Tags: ofnamedatemyplaceagofullbirth
1条回答
网友
1楼 · 发布于 2024-06-13 20:31:24

您可以使用列表类型为值的defaultdict,然后按对(键、值)读取每个列表,并将value添加到由key给出的list

from collections import defaultdict

result = defaultdict(list)
for values in my_list:
    for k, v in zip(values[::2], values[1::2]):
        result[k].append(v)

print(result)

给予

{
    "full name ": [
        " Arthur Schopenhauer",
        " Aristotle"
    ],
    "date of birth ": [
        " Friday, February 22, 1788 (232 years ago)",
        " 384 BC (2403 years ago)"
    ],
    "place of birth ": [
        " Gdansk, Pomorskie, Poland",
        " Halkidiki, Macedonia Central, Greece"
    ],
    "date of death ": [
        " Friday, September 21, 1860 (age: 72 years) ",
        " 322 BC (age: 62 years) "
    ],
    "place of death ": [
        " Frankfurt, Hesse, Germany",
        " Evvoia, Greece Central, Greece"
    ]
}

相关问题 更多 >