Katty_one
Katty_one

Reputation: 351

How to strip part of a string in dictionary key

I have a dictionary like this:

{'Country - USA': 'Approved',
'Country - Italy': 'Approved'}

I want to remove the from it Country - string. The output should be:

{'USA':'Approved',
'Italy':'Approved'}

I tried to use dict.items() somehow but I didn't succeed

Upvotes: 0

Views: 815

Answers (3)

enamya
enamya

Reputation: 111

str_to_delete = "Country - "
d = {'Country - USA': 'Approved', 'Country - Italy': 'Approved'}
d = {
 country.replace(str_to_delete, ""): value
 for country, value in d.items()
}
print(d)   # {'USA': 'Approved', 'Italy': 'Approved'}

Upvotes: 0

Sanath Manavarte
Sanath Manavarte

Reputation: 104

You can do with this code

x = {'Country - USA': 'Approved', 'Country - Italy': 'Approved'}

index_position = len('Country - ') - 1
x = {key[index_position:]: value for key, value in x.items()}

Upvotes: 0

MattDMo
MattDMo

Reputation: 102852

You're on the right trail with dict.items(). Here's a dictionary comprehension that will get you what you want:

d = {'Country - USA': 'Approved', 'Country - Italy': 'Approved'}
new = {key.split()[-1]:value for key, value in d.items()}
print(new)

outputs:

{'USA': 'Approved', 'Italy': 'Approved'}

We're taking the value of each key, splitting it on whitespace (the default argument), and taking the last piece. Of course, this will only work if the country has a 1-word name.

Another option is to simply remove "Country - ":

{key.lstrip("Country - "):value for key, value in d.items()}

or you can go by index:

{key[10:]:value for key, value in d.items()}

Upvotes: 1

Related Questions