简体   繁体   English

来自csv数据的Python字典,其关键值是字典

[英]Python dictionary from csv data whose key values are dictionaries

I have a file with the following data: 我有一个包含以下数据的文件:

even;0;even;1;odd
odd;0;odd;1;even

I want to create a dictionary with the keys being the first value on each line, even and odd, and the values being dictionaries with key values as the integers and values as the even or odd that follows. 我想创建一个字典,键是每行的第一个值,偶数和奇数,值是字典,其键值是整数,后面是偶数或奇数。 So is if I create a dictionary with this data it should print like this: 因此,如果我用此数据创建字典,它应该像这样打印:

{'even': {'0': 'even', '1': 'odd'}, 'odd': {'0': 'odd', '1': 'even'}}

This is my code: 这是我的代码:

def read_fa(file) -> dict:
d = {}
data = read_file_values(file)
for line in data:
    values = line.split(';')
    inner_values = values[1:]
    inner_value_inputs = []
    inner_value_states = []
    for iv in inner_values:
        try:
            type(eval(iv)) is int
            inner_value_inputs.append(iv)
        except:
            inner_value_states.append(iv)
    inner_value_tuples = list(zip(inner_value_inputs, inner_value_states))    
    d[values[0]] = ({t[0]: t[1]} for t in inner_value_tuples)
print(d)

The "read_file_lines()" function I have basically reads the file and if I put the contents in a list it prints: 我基本上已经读取了“ read_file_lines()”函数,如果将内容放入列表中,它将打印:

['even;0;even;1;odd', 'odd;0;odd;1;even']

The output I get with my code is this: 我的代码得到的输出是这样的:

{'even': <generator object <genexpr> at 0x02927A30>, 'odd': <generator object <genexpr> at 0x02927AA8>}

Instead of getting the second dict as the keys I get this generator. 我没有得到第二个字典作为键,而是得到了这个生成器。 Any help on how to fix this is appreciated, also any suggestions on compressing the code to make it more compact. 感谢您提供有关如何解决此问题的任何帮助,以及有关压缩代码以使其更紧凑的任何建议。

d[values[0]] = dict((t[0], t[1]) for t in inner_value_tuples)

要么

d[values[0]] = {t[0]: t[1] for t in inner_value_tuples}

You could also use itertools to slice up the input for you. 您还可以使用itertools为您分割输入。

import itertools as it

data = ['even;0;even;1;odd', 'odd;0;odd;1;even']

out = {}
for d in data:
    elems = d.split(';')
    key = elems[0]
    evens = it.islice(elems, 1, None, 2)
    odds = it.islice(elems, 2, None, 2)
    out[key] = {x: y for x, y in zip(evens, odds)}

print out

>>> {'even': {'1': 'odd', '0': 'even'}, 'odd': {'1': 'even', '0': 'odd'}}

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

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