python 能否从字典中的特定键获取随机行值

rta7y2nd  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(102)

我从.CSV文件中提取记录到Pandas Dataframe 中,然后我想在其中提取一个随机记录/行,而不使用特定关键字(如法语或英语)中的索引。甚至是一个特定行(如法语单词及其英语含义),并在特定关键字/行处显示提取的随机记录。

#  this is the .CSV file having French word and English meaning

French,English
partie,part
histoire,history
chercher,search
seulement,only
police,police
pensais,thought
aide,help
demande,request
genre,kind
mois,month
frère,brother
laisser,let
car,because
mettre,to put

Python代码:

data = pandas.read_csv("french_words.csv")

#----converting read .CSV file to dictionary

to_learn = data.to_dict(orient="records")

current_card = random.choice(to_learn)
print(current_card["French"])

#----This is what I want to achieve using dictionary 

#----This is what I tried but can't move forward

words_data_dict = {row.French: row.English for (index, row) in data.iterrows()}
ruoxqz4g

ruoxqz4g1#

我想出的解决办法

# read data from a dataframe into a dictionary
words_data_dict = {row.French: row.English for (index, row) in data.iterrows()}
print(words_data_dict)

# convert the dictionary to a list
list_of_entry = list(words_data_dict.items())
print(list_of_entry)

# generate a random row from the dictionary
random_data = random.choice(list_of_entry)

# specify Key using Index
print(random_data[0])

相关问题