Vigneshwaran Thenraj Vigneshwaran Thenraj - 1 year ago 89
Python Question

List of dictionary within dictionary using for loop

I am creating a random color for xlsxwriter in python

import random
point = []
dict1 = {}
for row_count in range(3):

fill = {
"color": '#' + ''.join([random.choice('0123456789ABCDEF') for x in range(6)]),
dict1['fill'] = fill
print fill
print point

Expected output

[{'fill': {'color': '#8C4372'}}, {'fill': {'color': '#5EF546'}}, {'fill': {'color': '#386CF4'}}]

Actual Output

{'color': '#8C4372'}
{'color': '#5EF546'}
{'color': '#386CF4'}
[{'fill': {'color': '#386CF4'}}, {'fill': {'color': '#386CF4'}}, {'fill': {'color': '#386CF4'}}]

How to solve this.

Thanks in advance

Answer Source

You may achieve the same using a list comprehension expression as:

[{'file': {'color': ''.join([random.choice('0123456789ABCDEF') for x in range(6)])}} for row_count in range(3)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download