0

I have a dictionary of phone numbers where number is Key and country is value. I want to update the key and add country code based on value country. I tried to use the map function for this:

print('**Exmaple: Update phone book to add Country code using map function** ')
user=[{'952-201-3787':'US'},{'952-201-5984':'US'},{'9871299':'BD'},{'01632 960513':'UK'}]

#A function that takes a dictionary as arg, not list. List is the outer part
def add_Country_Code(aDict):
            for k,v in aDict.items():
                if(v == 'US'):
                 aDict[( '1+'+k)]=aDict.pop(k)
                if(v == 'UK'):
                 aDict[( '044+'+k)]=aDict.pop(k)
                if (v == 'BD'):
                 aDict[('001+'+k)] =aDict.pop(k)
            return aDict

new_user=list(map(add_Country_Code,user))

print(new_user)

This works partially when I run, output below : [{'1+952-201-3787': 'US'}, {'1+1+1+952-201-5984': 'US'}, {'001+9871299': 'BD'}, {'044+01632 960513': 'UK'}]

Notice the 2nd US number has 2 additional 1s'. What is causing that?How to fix? Thanks a lot.

0

1 Answer 1

2

Issue

You are mutating a dict while iterating it. Don't do this. The Pythonic convention would be:

  1. Make a new_dict = {}
  2. While iterating the input a_dict, assign new items to new_dict.
  3. Return the new_dict

IOW, create new things, rather than change old things - likely the source of your woes.

Some notes

  • Use lowercase with underscores when defining variable names (see PEP 8).
  • Lookup values rather than change the input dict, e.g. a_dict[k] vs. a_dict.pop(k)
  • Indent the correct number of spaces (see PEP 8)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.