python - 如何在python中从文件中的字典中添加多个值

标签 python python-3.x file dictionary

给定一个文件 data.txt: 包含国家名称及其人口和面积的列表,该文件如下所示:

China|1,339,190,000|9,596,960.00
Brazil|193,364,000|8,511,965.00
Japan|127,380,000|377,835.00
Canada|34,207,000|9,976,140.00
Indonesia|260,581,100|1,809,590.97

我想创建一个包含国家名称(键)和两个值(人口和面积)的字典。

最终的输出应该是这样的:

China:[1339190000,9596960.00]

人口是整数,面积是 float 。

这是我的代码,我不知道我做错了什么,我想知道是否有人可以为我指出。

谢谢。

这是我的代码:

Country = {}
file = open("data.txt", "r")
for i in file :
  file1 = i.strip(",") 
  parts = i.split("|")
  length = len(file[i])
  if length in parts:
    Country[length][i] = file[i]
  else:
    Country[length] = {i: file[i]}
  print(parts)

最佳答案

你可以使用 Pandas ,read_csv并使用千位分隔符。

import pandas as pd

cols = ['Country','Pop','Area']
df = pd.read_csv(filename,sep="|",thousands=r',',header=None,names=cols,index_col=cols[0])
d = {t[0]:t[1:] for t in df.itertuples()}

d 现在是一个字典:

{'Brazil': (193364000, 8511965.0),
 'Canada': (34207000, 9976140.0),
 'China': (1339190000, 9596960.0),
 'Indonesia': (260581100, 1809590.97),
 'Japan': (127380000, 377835.0)}

旧代码

d = df.to_dict('i') # returns float instead of int
d = {t[0]:dict(zip(df.columns,t[1:])) for t in df.itertuples()} # use this instead

{'Brazil': {'Area': 8511965.0, 'Pop': 193364000},
 'Canada': {'Area': 9976140.0, 'Pop': 34207000},
 'China': {'Area': 9596960.0, 'Pop': 1339190000},
 'Indonesia': {'Area': 1809590.97, 'Pop': 260581100},
 'Japan': {'Area': 377835.0, 'Pop': 127380000}}

关于python - 如何在python中从文件中的字典中添加多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47580006/

相关文章:

python - sklearn 中带有partial_fit 的 GridSearchCV/RandomizedSearchCV

python - 如何提供来自 Google Appengine 图像服务的边长大于 1600 像素的图像?

python - 我可以仅克隆 Git 存储库中大小低于指定限制的文件吗?

python - 如何在for循环中从字典中获取单个值

linux - 合并、排序、维护行序

python - Django 组选项列表

python - Django onetoone 与用户的关系不使用查询

java - 有没有更好的替代 File.listFiles() 方法?

c++ - 第 0 行第 0 列错误 : bad conversion while loading YAML file

python - nltk Sentiwordnet 与 python 的结合使用