【发布时间】: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