I am trying to read from a csv file to a dictionary. The problem is that I have 3 values per line (not just 2) and want to transform to a dict where the first value is the key and the last 2 values are combined to a single value (eg using a list or a tuple). As an example, I have the following inside csv:
Calcium Enriched 100% Lactose Free Fat Free Milk,2346,57876.0
Large Organic Omega3 Brown Eggs,2568,86280.0
Roasted & Salted Shelled Pistachios,919,29358.0
Chocolate Peanut Butter Protein Bar,801,21296.0
...
I want the output to be something like this:
{'Calcium Enriched 100% Lactose Free Fat Free Milk': [2346,57876.0]}
{'Large Organic Omega3 Brown Eggs': [2568,86280.0]}
{'Roasted & Salted Shelled Pistachios': [919,29358.0]}
{'Chocolate Peanut Butter Protein Bar': [801,21296.0]}
I tried to do it the normal way like this:
with open('avg_prod_reorder_time.csv', 'r', encoding='utf-8') as csv_file:
reader = csv.reader(csv_file)
avg_prod_reorder_time = dict(reader)
But I get the following error:
ValueError: dictionary update sequence element #0 has length 3; 2 is required
How to fix this? Thanks.
You needn't use csv. Just read files line by line and split it.
with open("data.csv", 'r') as f:
for line in f:
key, *value = line.rstrip("\n").split(',')
result = {key: list(value)}
This creates a dict as you wanted:
avg_prod_reorder_time = {r[0]: r[1:] for r in reader if r}
A dict consists of key/value pairs, but your data is not formatted in pairs. The code above takes the first element as a key and forms a list of all remaining elements. The condition if r
skips empty rows.
Consider you have a csv file like this,
some.csv
Hello ,1,2
There ,2,3
Friend ,4,5
You can try this,
import csv
mydict = {}
with open("some.csv","r+") as c:
r = csv.reader(c)
for row in r:
mydict[row[0]] = row[1:]
print(mydict)
output:
{'Friend ': ['4', '5'], 'Hello ': ['1', '2'], 'There ': ['2', '3']}
Explanations:
This is the part where you'll be interested in,
r = csv.reader(c)
for row in r:
mydict[row[0]] = row[1:]
Here we are assigning
mydict[row[0]]
with row[1:]
ie for first one
mydict['Hello']
with row[1:]
ie [1,2]
# List slicing
Similarly for the other lines.
Note:
List slicing means slicing a list based on indexes, try this if you didn't know about them. The general form is like this,
your_list[start:stop]
Note Start is inclusive stop is exclusive
>>> a = [1,2,3,4]
>>> a[0]
1
>>> a[1:]
[2, 3, 4]
>>> a[2:]
[3, 4]
>>> a[3:]
[4]
>>> a[:2]
[1, 2]
>>> a[:3]
[1, 2, 3]
>>> a[:1]
[1]
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.