Python Generating million dictionaries

Python Generating a million dictionaries


Generating a million dictionaries

You can use a loop to generate a large number of dictionaries efficiently, if all the dictionaries start out with similar data.

#A million aliens
aliens = []

# Make a million green aliens, worth 5 points
# each. Have them all start in one row.
for alien_num in range(1000000):
 new_alien = {}
 new_alien['color'] = 'green'
 new_alien['points'] = 5
 new_alien['x'] = 20 * alien_num
 new_alien['y'] = 0
 aliens.append(new_alien)

#Prove the list contains a million aliens.
num_aliens = len(aliens)

print("Number of aliens created:")
print(num_aliens)

Screenshot 

generate dictionary

 

0 comments:

Post a Comment