See error message and dictionary below:
Traceback (most recent call last):
File "C:/Users/richarddoi/Desktop/blackjack/test blackjack csv.py", line 9, in <module>
for key,value in data:
ValueError: too many values to unpack (expected 2)
{'Ace of Hearts': 1, 'King of Hearts': 10, 'Queen of Hearts': 10, 'Jack of Hearts': 10, '10 of Hearts': 10, '9 of Hearts': 9, '8 of Hearts': 8, '7 of Hearts': 7, '6 of Hearts': 6, '5 of Hearts': 5, '4 of Hearts': 4, '3 of Hearts': 3, '2 of Hearts': 2, 'Ace of Spades': 1, 'King of Spades': 10, 'Queen of Spades': 10, 'Jack of Spades': 10, '10 of Spades': 10, '9 of Spades': 9, '8 of Spades': 8, '7 of Spades': 7, '6 of Spades': 6, '5 of Spades': 5, '4 of Spades': 4, '3 of Spades': 3, '2 of Spades': 2, 'Ace of Clubs': 1, 'King of Clubs': 10, 'Queen of Clubs': 10, 'Jack of Clubs': 10, '10 of Clubs': 10, '9 of Clubs': 9, '8 of Clubs': 8, '7 of Clubs': 7, '6 of Clubs': 6, '5 of Clubs': 5, '4 of Clubs': 4, '3 of Clubs': 3, '2 of Clubs': 2, 'Ace of Diamonds': 1, 'King of Diamonds': 10, 'Queen of Diamonds': 10, 'Jack of Diamonds': 10, '10 of Diamonds': 10, '9 of Diamonds': 9, '8 of Diamonds': 8, '7 of Diamonds': 7, '6 of Diamonds': 6, '5 of Diamonds': 5, '4 of Diamonds': 4, '3 of Diamonds': 3, '2 of Diamonds': 2}
This appears when I use the following code:
import json
with open('deckfile.json') as f:
data = [json.loads(line) for line in f]
for row in data:
print(row)
But at this point, when I try to print the key and the value, using this code:
for key,value in data:
print(key, value)
I get an error message. To date, I've used txt and binary files successfully. I've never used to a dictionary before in reading from a file.
My question is: what is meant by too many values? As far as I know, there is a dictionary with: the name of the card and the value of the card for every card in a 52 card deck. I used a convention to try to get the key and the value without a success.
In for key,value in data
, there are two problems:
data
is the list of dictionaries. You probably meant for key,value in row
.for key,value in row.items()
.My question is: what is meant by too many values?
for key,value in data
means that data
should be an iterable of pairs that get unpacked into key
and value
. But the first thing you get when iterating over data
is the big dictionary it contains. To try to unpack the dictionary into key, value
, Python iterates over the dictionary and gets all 52 keys, which is too many values.
Think of it this way: you wouldn't do:
for row in data:
key, value = row
because the row has many keys and values. Nor would you do:
for k in row:
key, value = k
because k
is a key of row
, which is a string. Hence we need .items()
.