Home > Back-end >  multiply keys of dictionary to each other
multiply keys of dictionary to each other

Time:07-09

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!

CodePudding user response:

First of all remove 'salaries':[2]*[3] from the first dict, and then run

If you want to update the existing dictionaries.

for t in teachers:
   t["salary"] = t["hours"] * t["payment"]

Note: make sure hours and payment should be numeric, if you are not sure, then you can convert it

for t in teachers:
    try:
        t["salary"] = int(t["hours"]) * float(t["payment"])
    except ValueError:
        pass  # fallback case

CodePudding user response:

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}]
  • Related