0

as the title indicates I am trying to assign two values to one key. I know that there are a few answers on this website out there but I am quite new to python and I don't really understand them. Therefore it would be great if you could explain why the answer is the answer. Anyway here is the code I am trying to execute

card = {'1 of hearts': '1', '2 of hearts': '2', 'ace of hearts':'1, 11'}
print(card['ace of hearts'])

As you may be able to see i am trying to create a simple blackjack game and so I want to assign both 1 and 11 to ace of hearts (not 1 or 11). However the code I have written above gives '1, 11'. Any help would be greatly appreciated

3
  • Aren't you getting what you asked for? Your key is string 'ace of hearts', your value is another string '1, 11', so what you see is what you get. I would propose to make value as list of ints. card = {'1 of hearts': [1], '2 of hearts': [2], 'ace of hearts':[1, 11]} Commented Dec 20, 2014 at 1:57
  • What kind of deck do you have that has a 1 of hearts card? Commented Dec 20, 2014 at 2:03
  • Good point just realised that :P Commented Dec 20, 2014 at 15:53

3 Answers 3

4

Using a dictionary, you can make the key an array.

card = {'1 of hearts': '1', '2 of hearts': '2', 'ace of hearts':["1", "11"]}

You can then access the first variable by using:

print(card['ace of hearts'][0])

You can then access the second variable by using:

print(card['ace of hearts'][1])

If you want to store the array in the key as integers, you should use:

card = {'1 of hearts': 1, '2 of hearts': 2, 'ace of hearts':[1, 11]}
Sign up to request clarification or add additional context in comments.

1 Comment

@dawg has a good point about storing the card values as int instead of string
1

Use a set or a list in the literal assignment:

card = {'1 of hearts': [1], '2 of hearts': [2], 'ace of hearts':[1, 11]}

You probably also want to use an integer vs a string, since you can use an int to add.

Comments

0

When you print card['ace of hearts'] you get a single string. To break it up and put it in a list you could split the elements by comma:

>>> print(card['ace of hearts'].split(', '))
['1', '11']

or it's better, as others have said, to use list from the start.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.