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

Python 如何删除字典中不需要的引号,python,dictionary,python-3.3,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、counts和avglen,值是冒号

我有这个档案:

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、counts和avglen,值是冒号后面的what。最后一部分。那将是字典中的一本字典

我有以下代码:

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': ''}

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

试试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}'
import json
f = open('my_file.txt','r')
my_dictionary = json.loads(f.read())
f.close()

print my_dictionary
您的python脚本将是这样的

'{"shorts": ["cat", "dog", "fox"], "longs": "supercalifragilisticexpialidocious", "mosts": ["dog", "fox"], "count": 13, "avglen": "5.6923076923076925", "cat": 3, "dog": 4, "fox": 4, "frogger": 1, "supercalifragilisticexpialidocious": 1}'
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}

太酷了

假设您的文件名为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'}}`

尝试
str.split(':')
作为开始。(我曾经尝试过,但失败了;有人能向OP解释为什么
file\u name
不是文件名吗?)如果最后一部分是字典中的字典,那么它的关键是什么?询问代码的问题必须表明对所解决问题的最低理解。包括尝试过的解决方案、它们不起作用的原因以及预期结果。另请参见:堆栈溢出问题检查表