Vortex
Vortex

Reputation: 27

Accessing parts of values in a dictionary

Got an assignment to write a program that performs actions on a given dictionary according to an integer of a user input

Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}

If the user input is 2, the program is supposed to print Maria's birth month ("3" - part of the string). If the user input is 4, the program is supposed to print the last hobby on the list ("act").

I tried:

user_input = input ("Please enter a number between 1 and 8: ")

if int(user_input) == 2:
    print(Celebrity["birth_date"[4:5])

if int(user_input) == 4:
    print (Celebrity["hobbies"[2]])

Both of these conditions end up giving me KeyErrors, how do I go about accessing only a part of a value?

Upvotes: 0

Views: 68

Answers (3)

DD_N0p
DD_N0p

Reputation: 229

When you want to get value you need to use key in square brackets. If you want get only mount you can get value by index. And if you want get last value in array you can use index -1 like this Celebrity["hobbies"][-1]

Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}

user_input = input ("Please enter a number between 1 and 8: ")

if int(user_input) == 2:
    print(Celebrity["birth_date"][4])

if int(user_input) == 4:
    print (Celebrity["hobbies"][-1])

Upvotes: 0

Irfan wani
Irfan wani

Reputation: 5094

Here you go;

Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}


user_input = input ("Please enter a number between 1 and 8: ")


if int(user_input) == 2:
print(Celebrity["birth_date"][4:5])

if int(user_input) == 4:
print (Celebrity["hobbies"][2])

You were placing brackets on the wrong spots, which were then getting "h" and "b" from "birth_date" and "hobbies" as keys.

Upvotes: 0

Bhargav Desai
Bhargav Desai

Reputation: 1016

Your syntax is Celebrity["birthdate"[4:5]) which create error. change it with Celebrity["birth_date"][4:5]. and Celebrity['hobbies[2]'] also create error change it with Celebrity["hobbies"][2].

Try this :

Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}
user_input = input ("Please enter a number between 1 and 8: ")

if int(user_input) == 2:
    print(Celebrity["birth_date"][4:5])

if int(user_input) == 4:
    print (Celebrity["hobbies"][2])

Output :

Please enter a number between 1 and 8: 2
3

Please enter a number between 1 and 8: 4
act

Upvotes: 1

Related Questions