简体   繁体   中英

how do I build a dictionary data inside a list?

I have this program:

def file(fname):
    lines = open(fname).read().splitlines()
    return(lines)
print(file('venue.txt'))

And it came out like this which I change into list:

['room 1,  10,  250']

How do I build a dictionary data with it, so that it can be like this:

[{'name': 'room 1', 'max': 10, 'cost': 250}]

Some clue maybe for me to build it. Thanks

Edited:

def file(fname):
    lines = open(fname).read().splitlines()
    new = []
    for i in lines:
        split = i.split(', ')
        new.append({'name':split[0],'max':split[1],'cost':split[2]})
    return(new)   
print(file('venue.txt'))

It prints:

new.append({'name':split[0],'max':split[1],'cost':split[2]})
IndexError: list index out of range

What does it mean?

If they are separated by ', ' you can use the split() on ', ' . Will return an array with the separated items.

For your example:

current_list = ['room 1,  10,  250']
split = current_list[0].split(',  ')
new_list = [{'name': split[0], 'max': int(split[1]), 'cost': int(split[2])}]
print(new_list)

output:

[{'name': 'room 1', 'max': 10, 'cost': 250}]

For a larger list:

current_list = ['room 1,  10,  250', 'room 2,  30,  500','room 3,  50,  850']
new_list = []
for i in current_list:
    split = i.split(',  ')
    new_list.append({'name': split[0], 'max': int(split[1]), 'cost': int(split[2])})

print(new_list)

output:

[{'name': 'room 1', 'max': 10, 'cost': 250}, {'name': 'room 2', 'max': 30, 'cost': 500}, {'name': 'room 3', 'max': 50, 'cost': 850}]

You can try this:

import re
def file(fname):
   lines = open(fname).read().splitlines()
   return(lines)
headers = ["name", "max", "cost"]
data1 = [re.split(",\s+", i) for i in file("venue.txt")]
final_data = [{a:b for a, b in zip(headers, data} for data in data1]
print(final_data)

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