如何删除字典中不需要的引号

时间:2013-11-24 16:44:57

标签: python dictionary python-3.3

我有这个文件:

shorts: cat, dog, fox 
longs: supercalifragilisticexpialidocious 
mosts:dog, fox 
count: 13 
avglen: 5.6923076923076925

cat 3 
dog 4 
fox 4 
frogger 1 
supercalifragilisticexpialidocious 1

我想将其转换为字典,其中的键为short,long,mosts,count和avglen,值为冒号后的值。最后一部分。这将是字典中的字典。

我有这段代码:

def read_report(filename):
list1 = [] 
d = {} 
file_name = open(filename)
for line in file_name:
    list1.append(line[:-1])
d = dict(zip(list1[::2], list1[1::2]))
file_name.close()
return d

结果是:

{'mosts: dog, fox': 'count: 13', 'shorts: cat, dog, fox': 'longs: supercalifragilisticexpialidocious', 'cat 3': 'dog 4', 'fox 4': 'frogger 1', 'avglen: 5.6923076923076925': ''}

如何清除不需要的冒号并更改引号的位置,使其看起来像一个有效的字典?

2 个答案:

答案 0 :(得分:0)

试用JSON,它是板载的标准库。你的文件看起来像这样。

'{"shorts": ["cat", "dog", "fox"], "longs": "supercalifragilisticexpialidocious", "mosts": ["dog", "fox"], "count": 13, "avglen": "5.6923076923076925", "cat": 3, "dog": 4, "fox": 4, "frogger": 1, "supercalifragilisticexpialidocious": 1}'

你的python脚本会是这样的。

import json
f = open('my_file.txt','r')
my_dictionary = json.loads(f.read())
f.close()

print my_dictionary

输出:

{u'count': 13, u'shorts': [u'cat', u'dog', u'fox'], u'longs': u'supercalifragilisticexpialidocious', u'mosts': [u'dog', u'fox'], u'supercalifragilisticexpialidocious': 1, u'fox': 4, u'dog': 4, u'cat': 3, u'avglen': u'5.6923076923076925', u'frogger': 1}

JSON!太酷了!

答案 1 :(得分:0)

假设您的文件名为txtfile.txt:

lines = open("txtfile.txt").readlines()
results = {}
last_part = {}
for line in lines:
    if line.strip() == "":
        continue
    elif line.startswith(tuple("shorts: longs: mosts: count: avglen:".split())):
        n, _, v = line.partition(":")
        results[n.strip()] = v.strip()
    else:
        n, v = line.split(" ")
        last_part[n.strip()] = v.strip()
results['last_part'] = last_part
print results

将输出:

{'count': '13', 'shorts': 'cat, dog, fox', 'longs': 'supercalifragilisticexpialidocious', 'mosts': 'dog, fox', 'avglen': '5.6923076923076925', 'last_part': {'frogger': '1', 'fox': '4', 'dog': '4', 'supercalifragilisticexpialidocious': '1', 'cat': '3'}}`