【问题标题】:How do I add lines to a key and different lines as values?如何将行添加到键和不同的行作为值?
【发布时间】:2022-12-01 01:23:48
【问题描述】:

所以我开始放置一个文件,其中列出了标题、演员、标题、演员等。

    12 Years a Slave
    Topsy Chapman
    12 Years a Slave
    Devin Maurice Evans
    12 Years a Slave
    Brad Pitt
    12 Years a Slave
    Jay Huguley
    12 Years a Slave
    Devyn A. Tyler
    12 Years a Slave
    Willo Jean-Baptiste
    American Hustle
    Christian Bale
    American Hustle
    Bradley Cooper
    American Hustle
    Amy Adams
    American Hustle
    Jeremy Renner
    American Hustle
    Jennifer Lawrence

我需要制作一本看起来像下面的字典,并列出电影中的所有演员

    {'Movie Title': ['All actors'], 'Movie Title': ['All Actors]}

到目前为止我只有这个

d = {}

with open(file), 'r') as f:
    for key in f:
        d[key.strip()] = next(f).split()

print(d)

【问题讨论】:

  • 在问题中将您自己的努力(代码)显示为格式正确的文本。
  • 你试过什么了?您显示的输出不是有效的 python,但 {'Movie Title': ['Actor', 'Actor']} 是一个字典,其中每个值都是一个列表。您检查电影是否已经在字典中(如果没有则添加电影加列表)然后附加到该列表。
  • 为什么你希望每个演员都在一个单独的列表中,而不是['Actor1', 'Actor2', ...]
  • defaultdict()dict.setdefault() 将有助于在您第一次遇到每个标题时自动将其初始化为空列表。

标签: python dictionary


【解决方案1】:

因此,您需要在读取标题和读取输入数据中的演员之间切换。您还需要存储标题,以便您可以在演员行中使用它。

您可以使用标题的设置在阅读标题和阅读演员之间切换。

一些关键检查,你有工作逻辑。

# pretty printer to make the output nice
from pprint import pprint


data = """    12 Years a Slave
    Topsy Chapman
    12 Years a Slave
    Devin Maurice Evans
    12 Years a Slave
    Brad Pitt
    12 Years a Slave
    Jay Huguley
    12 Years a Slave
    Devyn A. Tyler
    12 Years a Slave
    Willo Jean-Baptiste
    American Hustle
    Christian Bale
    American Hustle
    Bradley Cooper
    American Hustle
    Amy Adams
    American Hustle
    Jeremy Renner
    American Hustle
    Jennifer Lawrence"""


result = {}
title = None
for line in data.splitlines():
    # clean here once
    line = line.strip()
    if not title:
        # store the title
        title = line
    else:
        # check if title already exists
        if title in result:
            # if yes, append actor
            result[title].append(line)
        else:
            # if no, create it with new list for actors
            # and of course, add the current line as actor
            result[title] = [line]
        # reset title to None
        title = None

pprint(result)

输出

{'12 Years a Slave': ['Topsy Chapman',
                      'Devin Maurice Evans',
                      'Brad Pitt',
                      'Jay Huguley',
                      'Devyn A. Tyler',
                      'Willo Jean-Baptiste'],
 'American Hustle': ['Christian Bale',
                     'Bradley Cooper',
                     'Amy Adams',
                     'Jeremy Renner',
                     'Jennifer Lawrence']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2020-10-19
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多