Basic Nested Dictionary in a Loop
Ganesh Pal
ganesh1pal at gmail.com
Sun Apr 2 13:46:52 EDT 2017
On Sun, Apr 2, 2017 at 10:35 PM, Steve D'Aprano <steve+python at pearwood.info>
wrote:
>
> Why is payment a string?
>
> Yes it should be int
>
> > The value salary3 ,salary4,salary4 is to be generated in the loop . Iam
> > trying to optimize the above code , by looping as shown below
>
> In the above example, you have strings "salary3", "salary4", "salary5", but
> in the code below, you use 0, 1, 2 instead.
>
> Which do you intend to use?
>
> It must be Salary1,Salary2
> payment_list = [100, 200, 400, 500]
>
> employees = {}
> employees['emp_01'] = {}
> for salary, payment in enumerate(payment_list, 3):
> # I don't know why salary starts at 3 instead of 1 or 0.
> salary = 'salary' + str(salary)
> employees['emp_01'][salary] = dict(
> sex="f", status="single", exp="4", grade="A", payment=payment
> )
>
> from pprint import pprint
> pprint(employees)
>
>
> {'emp_01': {'salary3': {'exp': '4',
> 'grade': 'A',
> 'payment': 100,
> 'sex': 'f',
> 'status': 'single'},
> 'salary4': {'exp': '4',
> 'grade': 'A',
> 'payment': 200,
> 'sex': 'f',
> 'status': 'single'},
> 'salary5': {'exp': '4',
> 'grade': 'A',
> 'payment': 400,
> 'sex': 'f',
> 'status': 'single'},
> 'salary6': {'exp': '4',
> 'grade': 'A',
> 'payment': 500,
> 'sex': 'f',
> 'status': 'single'}}}
>
>
>
>
Thanks ;
Ganesh
More information about the Python-list
mailing list