繁体   English   中英

将文件中的数据放入字典中

[英]Putting data from file into a dictionary

我在用python工作。 我有一个名为data.txt的文件,其中包含

John:80,Emily:89,Smith:85,Josh:45,Watson:60  

我需要将此数据放入字典中,然后找到值的最大值,最小值和平均值。 我该如何从中创建字典?

这是我到目前为止的代码:

f= open('names.txt', 'r')
lines = f.readlines()
matrix = []
for line in lines:
    items = line.strip().split(',')
print items

开始了:

>>> data = 'John:80,Emily:89,Smith:85,Josh:45,Watson:60'
>>> pairs = data.split(',')
>>> pairs
['John:80', 'Emily:89', 'Smith:85', 'Josh:45', 'Watson:60']
>>> cast = lambda x: (x[0], int(x[1]))
>>> d = dict(map(lambda x: cast(x.split(':')), pairs))
>>> d
{'Josh': 45, 'Watson': 60, 'John': 80, 'Smith': 85, 'Emily': 89}
>>> max(d.values())
89
>>> min(d.values())
45
>>> float(sum(d.values())) / len(d)
71.8

要从文件读取数据:

with open('data.txt') as f:
    data = f.read()

当然,您必须通过检查边缘情况来更新此代码,例如空数据,错误输入,空dict等。

尝试这个:

import csv
reader = csv.reader(open('data.txt', 'r'))
dic = {}
for row in reader:
    key, value = row.split(':')
    dic[key] = int(value)

print dic

随您去..以下代码也处理两个经典问题:重复的条目和名称为空的条目。

txt=open('data.txt','r').read()
dic={}
mink,minv,maxk,maxv=None,None,None,None

# Populate dictionary 'dic' and calculate max and min values on the fly: 
for entry in txt.split(','):
    k,v=entry.split(':')
    v = int(v)
    if len(k)==0: continue
    dic[k]=v
    if not mink or v < minv : mink,minv = k,v
    if not maxk or v > maxv : maxk,maxv = k,v

# Compute average in second loop in case duplicate entries in 1st loop:
avg=0
for v in dic.values(): avg = avg + v
if len(dic)>0 : avg = avg / len(dic)    

print dic
print "Min:", mink, minv
print "Max:", maxk, maxv
print "Average:", avg
data = "John:80,Emily:89,Smith:85,Josh:45,Watson:60"

# alternative for data from file:
# data = open("file.txt").read().strip()

# split the data on every "," and ":" and convert the second value on each pair to an int.
data_dict = dict()
for entry in data.split(","):
    key, value = entry.split(":")
    data_dict[key] = int(value)

# dict() can take that array of two-element tuples (or lists) and parse it itself so the four lines above can be written as:
data_dict = dict(map(lambda person: (person[0], int(person[1])), [entry.split(":") for entry in data.split(",")]))

# smallest and biggest values:
min(data_dict.values())   # returns 45
max(data_dict.values())   # returns 89

# smallest and biggest key-value pairs:
min(data_dict.iteritems(), key=lambda x:x[1])   # returns ('Josh', '45')
max(data_dict.iteritems(), key=lambda x:x[1])   # returns ('Emily', '89')

# average value (check length != 0 first)
avg = sum(data_dict.values()) / float(len(data_dict))   # returns 71.8

# entry that is nearest to the average (dict needs at least one value)
nearest = data_dict.items()[0]
for key, value in data_dict.iteritems():
    if abs(value - avg) < nearest[1]:
        nearest = (key, value)
# nearest is ('Emily', 89)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM