将列表值附加到字典

append list values to a dictionary

Python 3.6.0

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

然后我创建了一个 key:value 对的字典,其中国家/地区 是关键,城市是价值。

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

示例:

城市 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']}

你懂的。

谢谢。

当您使用 [].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)

只需更改列表创建的位置

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)