Home > Net >  Python dictionary modification
Python dictionary modification

Time:12-09

This is a python code

def build_person(first_name, last_name, age=None):     
Return a dictionary of information about a person.
   person = {'first': first_name, 'last': last_name}     
   if age:         
      person['age'] = age     
   return person

I understand everything but the line

person['age'] = age

Because, "person" is a dictionary, and so if I want to modify it, shouldn't it accept a key-value pair? How can I modify it correctly ?

CodePudding user response:

Here, person[age] = age works only when age is given as argument when calling this function.

person is dictionary, age in person[age] is key, and the age which is at right side of assignment operator(=) is value passed as argument in function.

for e.g : for the given code below in last line i have given age as argument.

def build_person(first_name, last_name, age=None):     

   person = {'first': first_name, 'last': last_name}     
   if age:         
      person['age'] = age  
   print(person)   
   return person
build_person("yash","verma",9)

Output for above code is :

{'first': 'yash', 'last': 'verma', 'age': 9}

now, if i don't give age as a argument then,

def build_person(first_name, last_name, age=None):     

    person = {'first': first_name, 'last': last_name}     
    if age:         
        person['age'] = age  
    print(person)   
    return person
build_person("yash","verma")

output will be:

{'first': 'yash', 'last': 'verma'}

CodePudding user response:

person['age'] = age

The 'age' inside the brackets is the key, the value 'age' is where your value is assigned. The person dictionnary becomes:

 {'first': first_name, 'last': last_name,'age': age} 
  • Related