【问题标题】:append list values to a dictionary将列表值附加到字典
【发布时间】:2017-11-15 18:59:15
【问题描述】:

Python 3.6.0

我正在编写一个小程序,它以以下形式接受用户输入: 城市,国家

然后我创建一个键值对字典,其中国家 是关键,城市是价值。

但是,我希望价值(城市)部分成为一个列表,以便用户 可以进入同一个国家的多个城市。

例子:

城市 1,国家 1 城市1,国家2 城市2,国家1

我很接近这段代码:

destinations = {}
while True:
    query = input("Tell me where you went: ")
    if query == '':
        break
    temp = query.split(',')
    if len(temp) != 2:
        temp = []
        continue
    city = [query.split(',')[0]]
    country = query.split(',')[1]
    if country not in destinations:
        destinations[country] = city
    else:
        destinations[country].append(city)

我的问题是附加的城市也是他们自己的列表。这是来自 PyCharm:

destinations = {' country1': ['city1', ['city2']], ' country2': ['city1']}

我想要的是这个:

destinations = {' country1': ['city1', 'city2'], ' country2': ['city1']}

我明白为什么会发生这种情况,但是,如果每个城市都在自己的列表中,我似乎无法弄清楚如何将其他城市附加到列表中。

如果用户现在输入:city3, country1 那么目的地{}应该是:

destinations = {' country1': ['city1', 'city2', 'city3'], ' country2': ['city1']}

你明白了。

谢谢。

【问题讨论】:

  • 只需移动列表创建-city = query.split(',')[0](或city, country = query.split(','))然后destinations[country] = [city]。或使用collections.defaultdict(list)。

标签: list dictionary append python-3.6


【解决方案1】:

当您使用[].append([]) 附加列表时,会附加列表本身,而不是实际内容。你能做的和你目前的差不多,但是当你设置变量city时,把它设置为实际的文本本身,然后调整if语句中的代码。

destinations = {}
while True:
    query = input("Tell me where you went: ")
    if query == '':
        break
    temp = query.split(',')
    if len(temp) != 2:
        temp = []
        continue
    city = query.split(',')[0] //set city to the string and not the string in a list
    country = query.split(',')[1]
    if country not in destinations:
        destinations[country] = [city] //now the value for the key becomes an array
    else:
        destinations[country].append(city)

【讨论】:

    【解决方案2】:

    只需更改列表创建的位置

    destinations = {}
    while True:
        query = input("Tell me where you went: ")
        if query == '':
            break
        temp = query.split(',')
        if len(temp) != 2:
            temp = []
            continue
        city = query.split(',')[0]
        country = query.split(',')[1]
        if country not in destinations:
            destinations[country] = [city]  # <-- Change this line
        else:
            destinations[country].append(city)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2019-03-29
      相关资源
      最近更新 更多