Skip to main content
 首页 » 编程设计

python之如何创建值为集合的字典

2025年05月04日28傻小

我正在做一个练习,要求我构建两个字典,一个键是国家名称,值是 GDP。这部分工作正常。

第二个字典是我迷路的地方,因为键应该是字母 A-Z,值是国家/地区名称集。我尝试使用 for 循环,我在下面评论了问题所在。

如果用户输入的字符串只有一个字母(如 A),程序应打印出所有以该字母开头的国家/地区。但是,当您运行该程序时,它只会为每个字母打印出一个国家/地区。

文本文件包含 228 行。即:

1:Qatar:98900 
 
2:Liechtenstein:89400 
 
3:Luxembourg:80600 
 
4:Bermuda:69900 
 
5:Singapore:59700 
 
6:Jersey:57000 
 
etc. 

这是我的代码。

initials = [] 
countries=[] 
incomes=[] 
 
dictionary={} 
dictionary_2={} 
 
keywordFile = open("raw.txt", "r") 
 
for line in keywordFile: 
    line = line.upper() 
    line = line.strip("\n") 
    line = line.split(":")   
    initials.append(line[1][0])  # first letter of second element 
    countries.append(line[1])   
    incomes.append(line[2]) 
 
for i in range(0,len(countries)): 
    dictionary[countries[i]] = incomes[i] 

这个 for 循环应该吐出 248 个值(每个国家一个),其中键是初始值,值是国家名称。然而,它只吐出 26 个值(字母表中的每个字母对应一个国家/地区)

for i in range(0,len(countries)): 
    dictionary_2[initials[i]] = countries[i] 
    print(dictionary_2) 
 
while True: 
    inputS = str(input('Enter an initial or a country name.')) 
 
    if inputS in dictionary: 
        value = dictionary.get(inputS, "") 
        print("The per capita income of {} is {}.".format((inputS.title()), value )) 
 
    elif inputS in dictionary_2: 
        value = dictionary_2.get(inputS) 
        print("The countries that begin with the letter {} are: {}.".format(inputS, (value.title()))) 
 
    elif inputS.lower() in "quit": 
        break 
 
    else: 
        print("Does not exit.") 
 
print("End of session.") 

如果有任何意见能引导我走向正确的方向,我将不胜感激。

请您参考如下方法:

使用defaultdict 确保您的首字母字典的每个值都是一个集合,然后使用add 方法。如果您只是使用 = 每次都会覆盖初始键值,defaultdict 是一种更简单的使用表达式的方法,例如:

if initial in dict: 
    dict[initial].add(country) 
else: 
    dict[initial] = {country} 

请参阅下面的完整工作示例,还要注意我使用的是 enumerate 而不是 range(0,len(countries)),我也会这样做推荐:

#!/usr/bin/env python3 
from collections import defaultdict 
 
initials, countries, incomes = [],[],[] 
 
dict1 = {} 
dict2 = defaultdict(set) 
 
keywordFile = """ 
1:Qatar:98900 
 
2:Liechtenstein:89400 
 
3:Luxembourg:80600 
 
4:Bermuda:69900 
 
5:Singapore:59700 
 
6:Jersey:57000 
""".split("\n\n") 
 
for line in keywordFile: 
    line = line.upper().strip("\n").split(":") 
    initials.append(line[1][0]) 
    countries.append(line[1]) 
    incomes.append(line[2]) 
 
for i,country in enumerate(countries): 
    dict1[country] = incomes[i] 
    dict2[initials[i]].add(country) 
 
print(dict2["L"]) 

结果:

{'LUXEMBOURG', 'LIECHTENSTEIN'} 

参见:https://docs.python.org/3/library/collections.html#collections.defaultdict