简体   繁体   中英

How to append a unique list created within a for loop

I have a dataframe about movies

df = pd.read_csv("https://raw.githubusercontent.com/Giovanni1085/UvA_CSDA_2021/main/assignments/miniproject/Pudding-Film-Dialogue-Clean.csv"

It has the columns of gender and proportion_of_dialogue per film. The later shows the proportion of dialogue of each given character and the 'gender' columns shows of cours the gender.

I want to create a for loop that goes over every row and creates a new dictionary every time a row gives a new movie after several characters. I want in this dictionary list of the proportion of dialogue from woman and from man. This all together goes in it's own dictionary. The outcome would be something like:

What I have is this (it's a lot):

proportion_per_film_dictionary  = {}
prop_woman = 0
prop_man = 0

for i in range(len(df.index)):
  if df.loc[i,'index1'] == 0:           #I made a column with the index so I could do this for the first row
    dct['film_%s' %i] = []
    if df.loc[i, 'gender'] == 'woman':
      prop_woman = prop_woman + df.loc[i,'proportion_of_dialogue']
    if df.loc[i,'gender'] == 'man':
      prop_man = prop_man + df.loc[i,'proportion_of_dialogue']
    if df.loc[i,'title'] != df.loc[i+1,'title']:
      dct['film_%s'%i].append(prop_man)
      dct['film_%s'%i].append(prop_woman)
      proportion_per_film_dictionary.append(dct['film_%s'%i])
      prop_woman = None
      prop_man = None
  
  elif df.loc[i,'title'] == df.loc[i+1,'title']:
    if df.loc[i, 'gender'] == 'woman':
      prop_woman = prop_woman + df.loc[i,'proportion_of_dialogue']
    if df.loc[i,'gender'] == 'man':
      prop_man = prop_man + df.loc[i,'proportion_of_dialogue']
    
  elif df.loc[i,'title'] != df.loc[i+1, 'title']:
    if df.loc[i, 'gender'] == 'woman':
      prop_woman = prop_woman + df.loc[i,'proportion_of_dialogue']
    if df.loc[i,'gender'] == 'man':
      prop_man = prop_man + df.loc[i,'proportion_of_dialogue']
    if df.loc[i,'title'] != df.loc[i+1,'title']:
      dct['film_%s'%i].append(prop_man)
      dct['film_%s'%i].append(prop_woman)
      proportion_per_film_dictionary.append(dct['film_%s'%i])
      prop_woman = None
      prop_man = None

This code shows the iteration over every movie title, I first also tried i-1 but apparently Python doesn't do -1 , although it does +1 .

I now get the following error:

dict' object has no attribute 'append'

I don't know why. Anybody who can help me? Thank you

In python dictionaries you don't use append , that's for lists. For dictionaries, it's enough to add a new value by assigning a key. Like this:

dct['film_%s'%i] = prop_man
dct['film_%s'%i] = prop_woman

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM