2017-06-13 109 views
0

的Python 3.6.0追加列表值的字典

我写一个小程序,需要用户输入的形式: 城市,国家

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

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

例子:

city1,COUNTRY1 city1,COUNTRY2 城2,COUNTRY1

我靠近这个代码:

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

我得到为什么发生这种情况,但我似乎无法弄清楚如何添加额外的城市向没有每个城市都在自己的名单中。

如果现在用户输入:请分享帮助,然后COUNTRY1目的地{}应该是:

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

你的想法。

谢谢。

+0

只是移动列表创建 - '城市= query.split( '')[0]'(或'城市,国家=查询.split(',')'),然后'目标[国家] = [城市]'。或者使用'collections.defaultdict(list)'。 – jonrsharpe

回答

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) 
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] # <-- Change this line 
    else: 
     destinations[country].append(city)