读取文件并生成排序字典

时间:2016-09-23 20:20:52

标签: python dictionary

创建包含内容的文件:

Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5

读取此文件并使用类型为tuple的键和float类型的值创建一个字典,即字典的项应如下所示:

(‘Mary’,’Jane’) : 5.8

将此字典转换为元组列表。按降序对它们进行排序并打印出来。

我的代码是:

f = open('sam.txt', 'r')
answer = {}
tuple(answer.keys())
for i in answer:
    print tuple(answer.keys())  
for line in f:

    k, v = ((line.strip()).split(':'))
    answer[((k.strip()))] = float(v.strip())
print answer    
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()

在这里我得到的字典键是字符串而不是按照规定的元组请告诉我我的错误,请为我的问题做一些好的调整。

4 个答案:

答案 0 :(得分:0)

您还应该分割逗号','上的键,而不仅仅是 strip

answer[tuple(k.strip().split(','))] = float(v.strip())

另一方面,您不需要初始的dict特技代码:

answer = {}
with open('sam.txt') as f: # open with context manager does auto close
    for line in f:
        k, v = line.strip().split(':')
        answer[tuple(k.strip().split(','))] = float(v.strip())

答案 1 :(得分:0)

如果您将数据放在这样的新行中会更容易:

Mary,Jane : 5.8 
Mary,Doe : 6.0 
John,Doe : 6.3 
John,Muller : 5.6 
Mary,Muller : 6.5

然后代码将是:

f = open('data.txt', 'r')
answer = {}
for line in f:
    k, v = ((line.strip()).split(':'))
    key1, key2 = k.split(',')
    answer[(key1, key2)] = float(v.strip())

print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()

答案 2 :(得分:0)

我确实回答了这个可能我知道是否需要进一步升级才能提高效率

f = open('sam.txt')
answer = {tuple(x.split(':')[0].strip().split(',')): float(x.split('[1].strip()) for x in f}
print "\ndictionary taken from file is:\n"
print answer    
c = answer.items()
d = sorted(c)
print "\nafter sorted and converted into tuples the output is:\n"
print tuple(reversed(sorted(c)))
f.close()

答案 3 :(得分:0)

内置函数通常很有用,但有时您只需要一个简单的正则表达式:

# Generate file
txt = "Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5"
with open("out.txt","w+") as FILE: FILE.write(txt)

# Read file and grab content
content= [ re.findall(r"([A-Za-z]+),([A-Za-z]+)\s:\s([0-9]\.[0-9])",line) for line in tuple(open("out.txt","r")) ]

# Make dictionary
dct = {(k1,k2):float(v) for (k1,k2,v) in reduce(lambda x,y: x+y, content)}
print(dct)