简体   繁体   中英

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:

['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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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