简体   繁体   English

有没有更好的方法在 python 字典中找到特定值,如列表中?

[英]Is there a better way to find specific value in a python dictionary like in list?

I have been practicing on iterating through dictionary and list in Python.我一直在练习遍历 Python 中的字典和列表。

The source file is a csv document containing Country and Capital.源文件是包含 Country 和 Capital 的 csv 文档。 It seems I had to go through 2 for loops for country_dict in order to produce the same print result for country_list and capital_list.看来我必须通过 2 个 for 循环来为 country_dict 执行 go,以便为 country_list 和 capital_list 生成相同的打印结果。

Is there a better way to do this in Python dictionary?在 Python 字典中有没有更好的方法来做到这一点?

The code:编码:

import csv
path = #Path_to_CSV_File
country_list=[]
capital_list=[]
country_dict={'Country':[],'Capital':[]}
with open(path, mode='r') as data:
    for line in csv.DictReader(data):
        locals().update(line)
        country_dict['Country'].append(Country)
        country_dict['Capital'].append(Capital)
        country_list.append(Country)
        capital_list.append(Capital)

i=14 #set pointer value to the 15th row in the csv document

#---------------------- Iterating through Dictionary using for loops---------------------------
if i >= (len(country_dict['Country'])-1):
    print("out of bound")

for count1, element in enumerate(country_dict['Country']):
    if count1==i:
        print('Country = ' + element)

for count2, element in enumerate(country_dict['Capital']):
    if count2==i:
        print('Capital = ' + element)
#--------------------------------Direct print for list----------------------------------------

print('Country = ' + country_list[i] + '\nCapital = ' + capital_list[i])

The output: output:

Country = Djibouti
Capital = Djibouti (city)
Country = Djibouti
Capital = Djibouti (city)

The CSV file content: CSV文件内容:

Country,Capital
Algeria,Algiers
Angola,Luanda
Benin,Porto-Novo
Botswana,Gaborone
Burkina Faso,Ouagadougou
Burundi,Gitega
Cabo Verde,Praia
Cameroon,Yaounde
Central African Republic,Bangui
Chad,N'Djamena
Comoros,Moroni
"Congo, Democratic Republic of the",Kinshasa
"Congo, Republic of the",Brazzaville
Cote d'Ivoire,Yamoussoukro
Djibouti,Djibouti (city)
Egypt,Cairo
Equatorial Guinea,"Malabo (de jure), Oyala (seat of government)"
Eritrea,Asmara
Eswatini (formerly Swaziland),"Mbabane (administrative), Lobamba (legislative, royal)"
Ethiopia,Addis Ababa
Gabon,Libreville
Gambia,Banjul
Ghana,Accra
Guinea,Conakry
Guinea-Bissau,Bissau
Kenya,Nairobi
Lesotho,Maseru
Liberia,Monrovia
Libya,Tripoli
Madagascar,Antananarivo
Malawi,Lilongwe
Mali,Bamako
Mauritania,Nouakchott
Mauritius,Port Louis
Morocco,Rabat
Mozambique,Maputo
Namibia,Windhoek
Niger,Niamey
Nigeria,Abuja
Rwanda,Kigali
Sao Tome and Principe,São Tomé
Senegal,Dakar
Seychelles,Victoria
Sierra Leone,Freetown
Somalia,Mogadishu
South Africa,"Pretoria (administrative), Cape Town (legislative), Bloemfontein (judicial)"
South Sudan,Juba
Sudan,Khartoum
Tanzania,Dodoma
Togo,Lomé
Tunisia,Tunis
Uganda,Kampala
Zambia,Lusaka
Zimbabwe,Harare

I am not sure if I get your point;我不确定我是否明白你的意思; Please check out the code.请检查代码。

import csv
path = #Path_to_CSV_File
country_dict={}
with open(path, mode='r') as data:
    lines = csv.DictReader(data)
    for idx,line in enumerate(lines):
        locals().update(line)
        country_dict[idx] = {"Country":Country,"Capital":}

i=14 #set pointer value to the 15th row in the csv document

#---------------------- Iterating through Dictionary using for loops---------------------------
country_info = country_dict.get(i)
#--------------------------------Direct print for list----------------------------------------

print('Country = ' + country_info['Country'] + '\nCapital = ' + country_info['Capital'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在字典中创建/附加到列表值的更好方法 - Better way to create/append to a list value in a dictionary 在python中有更好的方法将功能列表应用于字典 - in python is there a better way to apply a list of functions to a dictionary 在python字典中找到特定的值 - find specific value in python dictionary Python json 按特定键值在列表中查找字典 - Python json find dictionary in list by specific key value 检查特定元素列表的更好方法 - python - Better way to check a list for specific elements - python 有没有更好的方法来获取具有列表作为值的 python 字典的 (key,itemN) 元组? - Is there a better way to get (key,itemN) tuples for python dictionary that has a list as a value? 有没有办法像 python 中的枚举列表一样查看字典? - Is there a way to see dictionary like an enumerate list in python? 在列表字典中找到最大列表范围的更好(更整洁)方法是什么 - What is the better(neater) way to find the largest list range in dictionary of lists 有没有更好的方法来动态地从字典列表中创建具有键和值的字典? - Is there a better way to create a dictionary with key and value from a list of dictionaries dynamically? 有没有更好的方法使用键但没有值将列表转换为Python中的字典? - Is there a better way to convert a list to a dictionary in Python with keys but no values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM