Basic Nested Dictionary in a Loop

Steve D'Aprano steve+python at pearwood.info
Sun Apr 2 13:05:07 EDT 2017


On Mon, 3 Apr 2017 02:13 am, Ganesh Pal wrote:

> Dear Python friend
> 
> 
> I have a nested  data dictonary in the below format and I need to store
> 1000 of  entries which are in teh below format
> 
> 
>>>> X['emp_01']['salary3'] = dict(sex="f", status="single", exp="4",
> grade="A",payment="200")
>>>> X['emp_01']['salary4'] = dict(sex="f", status="single", exp="4",
> grade="A",payment="400")
>>>> X['emp_01']['salary5'] = dict(sex="f", status="single", exp="4",
> grade="A",payment="400")

Why is payment a string?


> I only thing thats is changing is payment and I have payment_list as a
> list
> [100,200,400,500]:

And here payment is an 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?


>>>> X = {}
>>>> X['emp_01'] ={}
>>>> for salary in range(len(payment_list)):
> ...     X['emp_01'][salary] =  dict(sex="f", status="single", exp="4",
> grade="A",payment=payment_list[salary])


You should almost never need to write `range(len(payment_list))`.


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'}}}




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.



More information about the Python-list mailing list