I don’t have much experience in software design yet so I’m not sure how programmers typically solve this type of problem. I basically am creating some values and storing them in a dict, but the names are not unique. I know its not possible to store same key names in dicts but how do software engeeners get around this problem(I’m sure I’m not the first to face this)?
I think some code will make it easier to understand(two lists, one of animals and fruits, and then generating a random value between the two. I’m trying to figure out how to store this data so I can use it later):
lista = ['dog', 'cat', 'elephant', 'pig', 'bear']
listb = ['apple', 'pear']
dict_of_lists_values = {}
for list_a in lista:
for list_b in listb:
#print list_a, list_b
#print lista.index(list_a), listb.index(list_b), lista.index(list_a) * listb.index(list_b)
dict_of_lists_values[list_a] = [lista.index(list_a) * listb.index(list_b), list_b]
for lists_data in dict_of_lists_values:
print lists_data, ' holds ', dict_of_lists_values[lists_data]
You see the end result is:
elephant holds [2, 'pear']
pig holds [3, 'pear']
dog holds [0, 'pear']
bear holds [4, 'pear']
cat holds [1, 'pear']
which makes total sense because its overwriting the previous results(which would contain apple in the list of list and not pear). How can I redesign this if I want to store all 10 results and not just the unique 5?
thanks in advance.
You can use a combined key. For example you could use a tuple of a element from each list as key so you’d have:
And then to get the same output: