如何在python

时间:2017-11-30 21:32:12

标签: python python-3.x dictionary

我被给了两个档案。 file1包含国家/地区名称及其大陆的列表,例如:

Country,Continent
China,Asia
United States of America,North America
Brazil,South America

和file2包含国家/地区名称及其人口和区域的列表,例如:

Country|Population|Area
China|1,339,190,000|9,596,960.00
United States of America|309,975,000|9,629,091.00
Brazil|193,364,000|8,511,965.00

我想创建两个词典,一个用于file1,一个用于file2,然后我想组合所有具有相同键的值。 我的最终输出应该是这样的:

China:[193364000, 8511965.00, Asia]

如果总体是整数且面积是浮点数

我制作了两个字典,但我不知道如何将这些值组合在一起。

这是我的代码:

#first dictionary
Continent = {}
file2 = open("file2.txt", "r") 
for i in file2:
  file2 = i.strip
  parts2 = i.split(",") 
  Continent[parts2[0]] = parts2[1] 


#Second dictionary
Information = {}
file1 = open("file1.txt", "r")
for j in file1:
  file1 = j.strip
  part1 = j.split("|")
#Strip "," off from the values so that it's an intger/float
  part1[1] = part1[1].replace(",", "") 
  part1[2] = part1[2].replace(",", "")
  Information[part1[0]] = [part1[1], part1[2]]

4 个答案:

答案 0 :(得分:3)

好的,假设您填充了两个词典: 大陆,信息

假设两个词典都具有相同的键,这将起作用:

让我们假设:

Continent = {'china': 'Asia'}
Information = {'china': [193364000, 8511965.00]}
然后:
for key in Continent.keys():
    Information[key]=Information[key] + [Continent[key]]

会给:

Information = {'china': [193364000, 8511965.00, 'Asia']}

希望这有帮助。

答案 1 :(得分:1)

如果您可以保证密钥相同,则可以使用字典理解:

{country:Information[country] + [Continent[country]] for country in Continent}

答案 2 :(得分:1)

你可以试试这个:

continents = [i.strip('\n').split(',') for i in open('filename.txt')][1:-1]
country_data = [i.strip('\n').split('|') for i in open('filename.txt')][1:-1]
new_country_data = {a:[float(''.join(s.split(','))) for s in b]+[continents[a]] for a, b in country_data.items()}

答案 3 :(得分:1)

你不能将大陆的字符串类型与人口和列表的类型连接起来。区域数据。假设人口和区域数据作为列表值存储在file2 dict中。 试试这个:

dict1 = {"China":"Asia","United States of America":"North America","Brazil":"South America"}
dict2 = {"China":[1339190000,9596960.00],"United States of America":[309975000,9629091.00],"Brazil":[193364000,8511965.00]}
dict3 = {}

for country,continent in dict1.items():
    for country2 in dict2.keys():
        if country == country2:
            data = dict2[country2]
            data.append(continent)
            dict3.update({country:data})

print dict2