我的代码导致有缺陷的字典有什么问题?

时间:2018-02-09 14:21:16

标签: python python-3.x dictionary

所以我试图在字典中为每个键添加2个值作为列表(1个元素),我的项目在我的文件中看起来像这样:

['48', '0', 2550, 1651]
['33', '9', 5400, 3601]

其中前两个元素组合是关键,例如48-0是关键。 我的代码:

def dictionary(path_to_file):
    str_map = str.maketrans("", "", " []'\n")
    data = []
    with open(path_to_file, "r") as file:
        for line in file:
            line = line.translate(str_map)
            line = line.split(",")
            data.append(line)
    dict = defaultdict(list)
    for row in data:
        dict["-".join(row[:2])].append(row[2:])
    for x in list(dict.keys()):
        if dict[x] == []:
            del dict[x]
    return dict

我输出的一部分:

defaultdict(<class 'list'>,
            {'[1-0': [['5400', '3601]']],
             "[1-0/[['5400', '3601]']]": [],
             '[1-1': [['2550', '1651]']],
             "[1-1/[['2550', '1651]']]": [],

当我连续两次使用相同的密钥'[1-0': [['5400', '3601]']],然后"[1-0/[['5400', '3601]']]": [],我的代码中的问题导致此问题时,可以看到问题发生了

2 个答案:

答案 0 :(得分:1)

正如Jean-Francois Fabre所提到的,你应该使用ast.literal_eval而不是尝试使用字符串。这是一个简单的解决方案:

import ast

dct = {}
with open('yourfile.txt', 'r') as f:
    for line in f:
        item = ast.literal_eval(line)
        if (item[0] + '-' + item[1]) in dct:
            dct[item[0] + '-' + item[1]] += item[2:]
        else:
            dct[item[0] + '-' + item[1]] = item[2:]
print(dct)

这假定您的文件如下所示:

['48', '0', 2550, 1651]
['33', '9', 5400, 3601]

输出:

{'48-0': [2550, 1651], '33-9': [5400, 3601]}

答案 1 :(得分:-1)

我在本地运行您的代码段(Python 3),但无法察觉到任何错误,如下所示:

file

['48', '0', 2550, 1651]
['33', '9', 5400, 3601]

so-48707926.py

import os
from collections import defaultdict

def dictionary(path_to_file):
    str_map = str.maketrans("", "", " []'\n")
    data = []
    with open(path_to_file, "r") as file:
        for line in file:
            line = line.translate(str_map)
            line = line.split(",")
            data.append(line)
    dict = defaultdict(list)
    for row in data:
        dict["-".join(row[:2])].append(row[2:])
    for x in list(dict.keys()):
        if dict[x] == []:
            del dict[x]
    return dict

print(dictionary('file'))

输出:

defaultdict(<class 'list'>, {'48-0': [['2550', '1651']], '33-9': [['5400', '3601']]})

请仔细检查您的输入。