-1

I'm trying to add a user input to a key in dictionary that is used as a dataframe but I can't seem to make it to work. Here's what I've done:

import pandas as pd

teams = {
  "Team Ahab":["Venom","Quite"],
  "Team Ishmael":[ "Big Boss","EVA"]}

team_df = pd.DataFrame(teams)

user_choice = input("What is your name:")

teams.update({"Team Ahab":user_choice})

team_reader = pd.read_csv("All Teams.txt")

When I try to print my dataframe the user input does not come up in the text file that I used since this comes up

Team Ahab,Team Ishmael, Team Miller, Team Ocelot 
----------

Venom            John         Kaz       Alex

I'm planning on updating the values on the dictionary with the user input(their names) into a key which is their chosen team. Here's what I want to look like

user_choice = input("What is your name:") ("Paul")
teams.update({"Team Ahab":user_choice})
print(team_df)

My ideal output:

Team Ahab ,Team Ishmael, Team Miller, Team Ocelot
Venom            John         Kaz       Alex
Paul
  • Did you update the dataframe after the input ? Seems just updated the dict ? – SeaBean May 13 '21 at 17:43
  • How do you update a dataframe again? Sorry I'm new to panda – Paul Atreidis May 13 '21 at 17:47
  • What are you trying to do? Because currently you're turning a python `dict` into a dataframe with 2 rows. Then updating the initial python `dict` to replace the list of values with a single string. The writing out csv data to a .txt file from the unmodified dataframe. – Henry Ecker May 13 '21 at 17:56
  • I'm currently making a scoring system for a school that is going to be my project for my programming subject. I'm planning on updating the values on the dictionary with the user input(their names) into a key which is their chosen team. I'm bad at explaining things so please excuse me – Paul Atreidis May 13 '21 at 18:04
  • Can you update your question to outline what you are trying to do with sample input and expected output? – Henry Ecker May 13 '21 at 18:05
  • I'll do that now – Paul Atreidis May 13 '21 at 19:06

1 Answers1

0

The dictionary update() method overwrites all the old values for the key you pass to it, which is apparently not what you want. To add a name to a team in the dictionary, you could do this instead:

teams["Team Ahab"] += [user_choice]

This will update teams, but not the DataFrame you want to print, which is team_df. You could try to update the DataFrame too, by simply creating it again from the new version of the dictionary:

team_df = pd.DataFrame(teams)

But this will not work if the teams now have different numbers of members, because pd.DataFrame() requires that all lists of the dictionary (which are to become columns of the DataFrame) have the same length. See this question for a solution.

Arne
  • 9,990
  • 2
  • 18
  • 28