Basic Nested Dictionary in a Loop

Peter Otten __peter__ at web.de
Sun Apr 2 13:02:17 EDT 2017


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")
> 
> 
> I only thing thats is changing is payment and I have payment_list as a
> list
> [100,200,400,500]:
> 
> 
> The value salary3 ,salary4,salary4 is to be generated in the loop . Iam
> trying to optimize the above code , by looping as shown below
> 
> 
>>>> X = {}
>>>> X['emp_01'] ={}
>>>> for salary in range(len(payment_list)):

Whenever you feel the urge to write range(len(whatever)) -- resist that 
temptation, and you'll end up with better Python code ;)

> ...     X['emp_01'][salary] =  dict(sex="f", status="single", exp="4",
> grade="A",payment=payment_list[salary])
> ...
>>>> X
> {'emp_01': {0: {'grade': 'A', 'status': 'single', 'payment': 100, 'exp':
> '4', 'sex': 'f'}, 1: {'grade': 'A', 'status': 'single', 'payment': 200,
> 'exp': '4', 'sex': 'f'}, 2: {'grade': 'A', 'status': 'single', 'payment':
> 400, 'exp': '4', 'sex': 'f'}, 3: {'grade': 'A', 'status': 'single',
> 'payment': 500, 'exp': '4', 'sex': 'f'}}}
>>>>
> 
> 
> Any other suggestion ,   Please let me know  I am on python 2.7 and Linux

Instead of artificially blowing up your database change its structure. For 
example:

X["emp_01"] = dict(
    sex="f", 
    status="single", 
    exp="4", 
    grade="A",
    payments=[100, 200, 400, 500]
)




More information about the Python-list mailing list