Python - removing an item from a dictionary

Viewed 49

My goal for this code is to prompt a user for company, city, and state. After I print the data, I need to remove the city and then print the new data. When I run this code, it prints out the same data twice, basically not removing the city. Please help me understand when I split cityState why it's not then allowing me to remove the city.

Thanks for your help!

#Create a dictionary
user_data = {}

#Prompt for user data
company_name = input("Enter company name: ")
cityState = input("Enter company city and state: ")

#store the responses
user_data[company_name] = cityState

#print data
print("\nCompany details:")
for company_name, cityState in user_data.items():
    print(company_name + " " + cityState)

#split the data
temp = cityState.split()
user_data[temp[0]] = temp[1]

#remove the city
user_data.pop(temp[0])

#print the data
print("\nWith the city removed: ")
print(company_name + " " + cityState)
4 Answers

If you mean to separate city and state from the input, you can unpack the returning list from the call to cityState.split() to two variables:

city, state = cityState.split()
print("\nWith the city removed: ")
print(company_name + " " + state)

In the code, temp = cityState.split(), the split() value is returned into temp. The content of cityState doesn't change, which you happen to be printing at the end print(company_name + " " + cityState). Should do as mentioned by blhsing.

You may use del user_data[<your_key>]

Just note that you may be trying to delete a wrong key.

to update company_name key from your dict with only the state you should use:

user_data[company_name] = temp[1]

in your dict, the cityState variable is a string that holds both the city and the state, to remove the city means to remove the city from the string not to delete some key from your dict

Related