Sheikh Rahman
Sheikh Rahman

Reputation: 915

Update dictionary key inside list using map function -Python

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.

Upvotes: 0

Views: 732

Answers (1)

pylang
pylang

Reputation: 44525

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)

Upvotes: 2

Related Questions