user9367026
user9367026

Reputation: 3

Comparing a list value with Dictionary

I am trying to randomly pick a state from the available state (key): capital(value) dictionary list and then try to match the state picked against the dictionary to return the capital city.

My code so far:

capitals = {
'Alabama' : 'Montgomery',
'Alaska' : 'Juneau',
'Arizona' : 'Phoenix',
'Arkansas' : 'Little Rock',
'California' : 'Sacramento',
'Colorado' : 'Denver',
'Connecticut' : 'Hartford',
'Delaware' : 'Dover',
'Florida' : 'Tallahassee',
'Georgia' : 'Atlanta',
'Hawaii' : 'Honolulu',
'Idaho' : 'Boise',
'Illinois' : 'Springfield'}

name_list=list(zip(capitals.keys()))
print(name_list)

from random import *
random_state=list(choice(name_list))
print(random_state)

for key,value in capitals.items():
    if random_state in  key:
        print(value)

I am getting an error

TypeError: 'in ' requires string as left operand, not list

Expected output is Denver if the random state picked was Colorado

Thanks

Upvotes: 0

Views: 191

Answers (4)

NikitaZakharov
NikitaZakharov

Reputation: 61

You get TypeError because random_state is tuple of one element and you try to check if tuple contains in key which is string.

['Florida'] in 'Alabama'

Just remove zip from your code and you will get list of strings, however now you have list of tuples. And your code will check if string contains in string.

Upvotes: 0

G_M
G_M

Reputation: 3382

>>> from random import choice
>>> capitals = {
...     'Alabama': 'Montgomery',
...     'Alaska': 'Juneau',
...     'Arizona': 'Phoenix',
...     'Arkansas': 'Little Rock',
...     'California': 'Sacramento',
...     'Colorado': 'Denver',
...     'Connecticut': 'Hartford',
...     'Delaware': 'Dover',
...     'Florida': 'Tallahassee',
...     'Georgia': 'Atlanta',
...     'Hawaii': 'Honolulu',
...     'Idaho': 'Boise',
...     'Illinois': 'Springfield'
... }
>>> random_state = choice(list(capitals))
>>> capitals[random_state]
'Springfield'

Upvotes: 2

Aaron Lael
Aaron Lael

Reputation: 188

All of what you have seems to be replaceable by this since you're only pulling back one state with choice.

import random
print(capitals[random.choice(list(capitals))])

Since it's just one state, this just pulls back the value of that key directly instead of using a for loop to look through all of the keys.

Upvotes: 0

Will S
Will S

Reputation: 1

You have two problems.

First, you aren't generating name_list correctly. It should just be:

name_list=capitals.keys()

Second, generate random_state as a list. Get rid of the list() and it should work:

random_state=choice(name_list)

Upvotes: 0

Related Questions