My problem is this, when given any input (correctly formatted) the dictionary dancer_placings
is not correctly generated based on my code. An input of 1 dancer, with number 1, 2 dances, named foo and bar, the dictionary dancer_placings
is {'1': {'bar': 0}}
, when I want it to be {'1': {'foo': 0},{'bar': 0}}
I have obviously made a mistake, so how can I fix my code so that it does what I intend it to do?
Here is my code:
print("Welcome to Highland Scrutineer")
dancers = []
dances = []
dancer_placings = {}
dancers = []
dancer_num = int(input("How many dancers were there?: "))
while len(dancers) + 1 <= dancer_num:
dancers.append(input("What was the number of the dancer? "))
print("The list of dancers is:")
for dancer in dancers:
print(dancer)
dances = []
dance_num = int(input("How many dances did these dancers compete in? "))
while len(dances) + 1 <= dance_num:
dances.append(input("What was the name of the dance? "))
print("The list of dances is:")
for dance in dances:
print(dance)
for dancer in dancers:
for dance in dances:
dancer_placings.update({dancer:{}})
dancer_placings[dancer].update({dance:0})
print(dancer_placings)
Your code has a few problems, but I'll just address the ones to make your use case work:
That's not necessary. That should be up an indentation level.
Try this:
print("Welcome to Highland Scrutineer")
dancers = []
dances = []
dancer_placings = {}
dancers = []
dancer_num = int(input("How many dancers were there?: "))
while len(dancers) + 1 <= dancer_num:
dancers.append(input("What was the number of the dancer? "))
print("The list of dancers is:")
for dancer in dancers:
print(dancer)
dances = []
dance_num = int(input("How many dances did these dancers compete in? "))
while len(dances) + 1 <= dance_num:
dances.append(input("What was the name of the dance? "))
print("The list of dances is:")
for dance in dances:
print(dance)
for dancer in dancers:
dancer_placings[dancer] = []
for dance in dances:
dancer_placings[dancer].append({dance:0})
print(dancer_placings)
Thus, this results in the following output:
user-macbookpro2:~ user$ python test.py
Welcome to Highland Scrutineer
How many dancers were there?: 1
What was the number of the dancer? 1
The list of dancers is:
1
How many dances did these dancers compete in? 2
What was the name of the dance? 'foo'
What was the name of the dance? 'bar'
The list of dances is:
foo
bar
{1: [{'foo': 0}, {'bar': 0}]}
That appears to be your desired answer!