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?
#1
How to change part of the value string in Python Dictionary?

recs = {1: ['Susan Smith', '[email protected]'], 2: ['Cole Brown', '[email protected]'], 3: ['Sue John', '[email protected]']}


How to change .com to .org? The remaining value will be same.

Thanks
Reply
#2
Try this to see if helps,

recs = {1: ['Susan Smith', '[email protected]'], 2: ['Cole Brown', '[email protected]'], 3: ['Sue John', '[email protected]']}
print(recs)
temp=[]
for key,val in recs.items():
	for j in val:
		temp.append(j.replace(".com", ".org"))
		recs[key]=temp
	temp=[]
print(recs)
Output:
python test1.py {1: ['Susan Smith', '[email protected]'], 2: ['Cole Brown', '[email protected]'], 3: ['Sue John', '[email protected]']} {1: ['Susan Smith', '[email protected]'], 2: ['Cole Brown', '[email protected]'], 3: ['Sue John', '[email protected]']}
Best Regards,
Sandeep

GANGA SANDEEP KUMAR

User has been warned for this post. Reason: Providing a homework solution
Reply
#3
This is homework and no effort shown....

However, for learning purposes I provide alternative which should be shorter and without using 'temp':

>>> recs = {1: ['Susan Smith', '[email protected]'],
            2: ['Cole Brown', '[email protected]'],
            3: ['Sue John', '[email protected]']}
>>> for key in recs:
...     recs[key] = [item.replace('.com', '.org') for item in recs[k]]
...
>>> recs
{1: ['Susan Smith', '[email protected]'],
 2: ['Cole Brown', '[email protected]'],
 3: ['Sue John', '[email protected]']}
If values are consistent and their structure doesn't change then no need to iterate over all items and rebuild the whole list, only change second value (changing .org back to .com):

>>> for key in recs: 
...     recs[key][1] = recs[key][1].replace('.org', '.com') 
...      
>>> 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
#4
recs = {1: ['Susan Smith', '[email protected]'],
            2: ['Cole Brown', '[email protected]'],
            3: ['Sue John', '[email protected]']}
for key in recs:
    recs[key] = [item.replace('.com', '.org') for item in recs[key]]
Thank U


Sir,
recs[key]= how the whole record is being stored? Here key means 1,2,3, but the value also being stored. Please explain how this key works.
Reply
#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
#6
Hi All,

I am a self learner. I am not part of any educational institute. I collected some books and material and working on them.

Even though I completed one basic course I could not get the idea of this replace and append trick. Now I started another course.

I appreciate if some one can advise me on how to train the brain to think certain way. Are there any brain exercises to improve my thinking?

Thank U.
Reply
#7
(Feb-09-2020, 03:01 AM)sbabu Wrote: I appreciate if some one can advise me on how to train the brain to think certain way. Are there any brain exercises to improve my thinking?

One advice is keep practicing (mandatory for learning any language, whether spoken or programming). Second is use built in help (even if you understand very little of it at the beginning).

One possible scenario: you have string of numbers and need to manipulate it certain way - make all strings same length and padd with zeros if needed to achieve required length. '123' -> '000123', '123456' -> '123456'.

In interactive interpreter:

>>> s = '123'
What can I do with it? Lets have a look at built in methods available to s (which happens to be a str):

>>> s.       # 2 x TAB key
s.capitalize(   s.find(         s.isdecimal(    s.istitle(      s.partition(    s.rstrip(       s.translate(   
s.casefold(     s.format(       s.isdigit(      s.isupper(      s.replace(      s.split(        s.upper(       
s.center(       s.format_map(   s.isidentifier( s.join(         s.rfind(        s.splitlines(   s.zfill(       
s.count(        s.index(        s.islower(      s.ljust(        s.rindex(       s.startswith(  
s.encode(       s.isalnum(      s.isnumeric(    s.lower(        s.rjust(        s.strip(       
s.endswith(     s.isalpha(      s.isprintable(  s.lstrip(       s.rpartition(   s.swapcase(    
s.expandtabs(   s.isascii(      s.isspace(      s.maketrans(    s.rsplit(       s.title( 
I can scan all the names and pick most promising to find whether they are suitable for my purpose. Here I see zfill which may or not may mean 'zero fill'. How to find out?

>>> help(s.zfill)                         # or str.zfill
Help on built-in function zfill:

zfill(width, /) method of builtins.str instance
    Pad a numeric string with zeros on the left, to fill a field of the given width.
    
    The string is never truncated.
# press Q to close help and return to interactive interpreter
Seems something just about right. Lets try:

>>> s.zfill(6)
'000123'
>>> '123456'.zfill(6)
'123456'
>>> '1'.zfill(6)
'000001'
>>> ''.zfill(6)
'000000'
We have achieved our objective without leaving Python. You can check other string methods to find out what they do, same with other datatypes (lists, tuples, dictionaries etc). This way you don't need to reinvent wheel and can take advantage features which are already built in into language.
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
#8
>>> s.       # 2 x TAB key
s.capitalize(   s.find(         s.isdecimal(    s.istitle(      s.partition(    s.rstrip(       s.translate(   
s.casefold(     s.format(       s.isdigit(      s.isupper(      s.replace(      s.split(        s.upper(       
s.center(       s.format_map(   s.isidentifier( s.join(         s.rfind(        s.splitlines(   s.zfill(       
s.count(        s.index(        s.islower(      s.ljust(        s.rindex(       s.startswith(  
s.encode(       s.isalnum(      s.isnumeric(    s.lower(        s.rjust(        s.strip(       
s.endswith(     s.isalpha(      s.isprintable(  s.lstrip(       s.rpartition(   s.swapcase(    
s.expandtabs(   s.isascii(      s.isspace(      s.maketrans(    s.rsplit(       s.title( 
How did u get this list got printed. I mean by using just "s."

I tried Jupyter, Thonny, Anaconda. It did not work.

Thanks.
Reply
#9
(Feb-10-2020, 02:39 AM)sbabu Wrote: I tried Jupyter, Thonny, Anaconda. It did not work.

It works this way in interactive interpreter.

In Jupyter (which is not interactive interpreter per se) using ! at the beginning !s. + 2 x TAB delivers comparable result. The layout is little bit different but information is the same. You can do command line stuff with ! inside Jupyter/ipython as well (!pwd, !cd etc, some of commands work without !).

In Thonny it works in command prompt (lower block with >>> at the beginning of rows), layout somewhat similar to Jupyter.
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
#10
This is on Jupiter

!s. + 2 x TAB

Error:
's.' is not recognized as an internal or external command, operable program or batch file.
This is Thonny Command prompt
>>> s = 123
>>> s.
File "<stdin>", line 1
s.
^
SyntaxError: invalid syntax
>>> !s.
File "<stdin>", line 1
!s.
^
SyntaxError: invalid syntax
>>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split string into 160-character chunks while adding text to each part iambobbiekings 9 9,583 Jan-27-2021, 08:15 AM
Last Post: iambobbiekings
  struggling with one part of python Lucifer 23 6,472 May-08-2020, 12:24 PM
Last Post: pyzyx3qwerty
  From string parameter to a dictionary Mitchie87 9 3,100 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