Vigneshwaran Thenraj Vigneshwaran Thenraj - 2 months ago 37
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


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)]