Python Forum
How to change part of the value string in Python Dictionary?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to change part of the value string in Python Dictionary?
#5
How it works?

for key in recs: --> iterates over dictionary keys --> 1, 2, 3

recs[key] = --> assign/bound value to key in dictionary with name recs --> recs[1], recs[2], recs[3]

[item.replace('.com', '.org') for item in recs[key]] --> new value which assigned/bound to key, created with list comprehension from existing value, in spoken languaga something like 'give item where .com is replaced with .org for every item in existing values'

This can be written as dictionary comprehension as well:

>>> recs = {1: ['Susan Smith', '[email protected]'],
...             2: ['Cole Brown', '[email protected]'],
...             3: ['Sue John', '[email protected]']}
>>> recs = {key: [item.replace('.com', '.org') for item in recs[key]] for key in recs}
>>> recs
{1: ['Susan Smith', '[email protected]'], 2: ['Cole Brown', '[email protected]'], 3: ['Sue John', '[email protected]']}
>>> recs = {key: [item.replace('.org', '.com') for item in value] for key, value in recs.items()}
>>> recs
{1: ['Susan Smith', '[email protected]'], 2: ['Cole Brown', '[email protected]'], 3: ['Sue John', '[email protected]']}
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: How to change part of the value string in Python Dictionary? - by perfringo - Feb-08-2020, 07:20 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Split string into 160-character chunks while adding text to each part iambobbiekings 9 9,933 Jan-27-2021, 08:15 AM
Last Post: iambobbiekings
  struggling with one part of python Lucifer 23 6,894 May-08-2020, 12:24 PM
Last Post: pyzyx3qwerty
  From string parameter to a dictionary Mitchie87 9 3,386 Oct-12-2019, 10:34 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020