Tony Stark
Tony Stark

Reputation: 302

Python: Replace a specific word in value of dictionary

I have a dictionary

a = {'url' : 'https://www.abcd.com'}

How to use replace and removed 'https://www.' and just be 'abcd.com'?

I tried

a = [w.replace('https://www.', '') for w in a]

But it only return the key. Thanks!

Upvotes: 2

Views: 69

Answers (5)

Hamza Madni
Hamza Madni

Reputation: 11

You access the values of the dictionary using: a['url'] and then you update the string value of url using the replace function:

a['url'] = a['url'].replace('https://www.', '')

Upvotes: 1

Eiks
Eiks

Reputation: 48

if you want your result to be a dictionary:

a = {k: v.replace('https://www.', '') for k, v in a.items()}

if you want your result to be an array:

a = [v.replace('https://www.', '') for v in a.values()]

More on dictionary comprehension here: https://www.python.org/dev/peps/pep-0274/

Upvotes: 0

Armadillan
Armadillan

Reputation: 578

The syntax for dict comprehension is slightly different:

a = {key: value.replace('https://www.', '') for key, value in a.items()}

As per documentation: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

And https://docs.python.org/3/tutorial/datastructures.html#looping-techniques for dict.items().

Upvotes: 0

not_speshal
not_speshal

Reputation: 23146

If your dictionary has more entries:

a_new = {k:v.replace('https://www.', '') for k,v in a.items()]

Upvotes: 1

azro
azro

Reputation: 54148

There is nothing to iterate on, just retrieve the key, modify it, and save it

a = {'url': 'https://www.abcd.com'}
a['url'] = a['url'].replace('https://www.', '')
print(a)  # {'url': 'abcd.com'}

Upvotes: 0

Related Questions