Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

multiply keys of dictionary to each other

the dictionary I have is:

teachers = [
    {'Name':'Mahdi Valikhani', 'phoneN':'+989012345679', 'hours':6, 'payment':50000, 'salaries':[2]*[3]},
    {'Name':'Ali Afaghi', 'phoneN':'+989011234567', 'hours':8, 'payment':45000},
    {'Name':'Hossein Alizadeh', 'phoneN':'+989011234867', 'hours':8, 'payment':45000},
]

and I want to somehow multiply hours to payment to have the salary!
I have tried multiplying but it gives me an error and the error says you can not multiply strings into integers!

help please!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Iterate over each dict and compute salaries and add new key and value like below:

teachers = [
    {'Name':'Mahdi Valikhani', 'phoneN':'+989012345679', 'hours':6, 'payment':50000},
    {'Name':'Ali Afaghi', 'phoneN':'+989011234567', 'hours':8, 'payment':45000},
    {'Name':'Hossein Alizadeh', 'phoneN':'+989011234867', 'hours':8, 'payment':45000},
]

for dct in teachers:
    dct['salaries'] = dct['hours']*dct['payment']
    
print(teachers)

Output:

[{'Name': 'Mahdi Valikhani', 'phoneN': '+989012345679', 'hours': 6, 'payment': 50000, 'salaries': 300000}, 
{'Name': 'Ali Afaghi', 'phoneN': '+989011234567', 'hours': 8, 'payment': 45000, 'salaries': 360000}, 
{'Name': 'Hossein Alizadeh', 'phoneN': '+989011234867', 'hours': 8, 'payment': 45000, 'salaries': 360000}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading