Can I make the age value calculable based on year of birth inside a dictionary?

Question:

I am new to Python, and I want to know if there is a way to make the age value calculated using the year of birth which is an item with the age in the same dictionary.

This is what it came to my mind, and I think there is simple way like this without using additional variables of functions.

person = {
          'name': Jane,
          'yearofbirth': 1995,
          'yearnow': 2019,
          'age': person['yearnow'] + person['yearofbirth']
        }

Any help would be appreciated. Thank you!

Asked By: Mourad gh

||

Answers:

You may have self referential dictionary by using a class derived from dict but dict itself doesn’t have this capability. The following code is taken from this answer.

class MyDict(dict):
   def __getitem__(self, item):
       return dict.__getitem__(self, item) % self

dictionary = MyDict({

    'user' : 'gnucom',
    'home' : '/home/%(user)s',
    'bin' : '%(home)s/bin' 
})


print dictionary["home"]
print dictionary["bin"]
Answered By: ramazan polat

Yes, you can
Just not decalre the whole dict in one act

person = {
          'name': Jane,
          'yearofbirth': 1995,
          'yearnow': 2019
         }
person["age"] = (lambda yearnow, yearofbirth: yearnow - yearofbirth)(**person)

But in your example you shouldn’t change anything, because there is no way to simplify it(easily). My solution should be used only in complicated tasks. I just you the way to simplify it in case of a huge amount of values in dict.

Answered By: Mr Morgan

Instead of hardcoding the current year, you could get python to give it to you

from datetime import datetime

currentYear = datetime.now().year


person = {
          'name': 'Jane',
          'yearofbirth' : 1995

        }

age = currentYear - person.get( "yearofbirth", "") 
person.update({'age': age})

print(person)

You can’t set your age inside the dict, as it has not been defined yet.

If you do like above code, we are setting the age outside the dict, then updating the dict with the value we just calculated based on currentYear and the age

The output is:

{'name': 'Jane', 'yearofbirth': 1991, 'age': 24}
Answered By: sykezlol
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.