Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading