Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Python) Creating a list with a unique automatically generated name [duplicate]

Tags:

python

list

I am trying to automate populating a town by randomly generating households. I generate the name of the town, generate the number of households, the last name of each household and number of occupants in each. That much is fine. I am now, however, trying to create each individual, to generate a first name, a sex, an age and an occupation, and I'd like to store this data in a list as well, one list containing the attributes of each person. The problem I'm running into is that I want to use a for loop, something like:

    #houseArray[currentFam][1] is the number of members in the current house. 
    for currentFam in range(houseArray[currentFam][1]):
        uniquelyNamedArray[0] = genSex()
        uniquelyNamedArray[1] = genFirstName()
        uniquelyNamedArray[2] = genAge()

So... look at the data of the first household, use a for loop to iterate through each member assigning stats, then go to the next household and do the same, progressing through each household. My problem lies in not knowing how to assign a unique name to each array created by the for loop. It doesn't really matter what the name is, it could be anything as long as each person has their own uniquely named array storing their attributes.

like image 862
CromerMW Avatar asked Mar 15 '26 05:03

CromerMW


2 Answers

Use a dictionary with the person's name as the key. Like:

people = {}
people["Billy Bloggs"] = ['23','Male','263 Evergreen Tce'] # store to dict
print ( people["Billy Bloggs"] ) # get stuff out of dict

Better still, give the attributes names by storing those as a dict as well:

people["Billy Bloggs"] = { 'Age':23, 'Gender':'M', 'Address':'263 Evergreen Tce' }
print ( people["Billy Bloggs"]['Age'] ) # Get billy's age

You can loop through the elements of a dictionary using the following syntax:

>>> mydict = {'a':'Apple', 'b':'Banana', 'c':'Cumquat'}
>>> for key, value in mydict.iteritems():
...     print ('Key is :' + key + ' Value is:' + value)
... 
Key is :a Value is:Apple
Key is :c Value is:Cumquat
Key is :b Value is:Banana

Note that there is no guarantee on the order of the data. You may insert data in the order A, B, C and get A, C, B back.

Note: The keys of a dict, in this case the person's name, are constrained to be unique. So if you store data to the same name twice, then the first key:value pair will be overwritten.

mydict["a"] = 5
mydict["a"] = 10
print (mydict["a"]) # prints 10

Sidenote: some of your gen*() functions could almost certainly be replaced by random.choice():

import random
first_names = ['Alice','Bob','Charlie','Dick','Eliza']
random_first_name = random.choice(first_names)
like image 101
Li-aung Yip Avatar answered Mar 17 '26 04:03

Li-aung Yip


Keep data out of your variable names and just store them in a dict.

like image 40
wim Avatar answered Mar 17 '26 02:03

wim