我现在有一本有六个键的字典,这些键的理想顺序如下:
order_of_keys = ["id", "question", "choice1", "choice2", "choice3", "choice4", "solution"]
现在,这些键中的每一个都对应于一个包含所有可能值的字典。我构建这本词典的方式是通过熊猫读者(不确定这是否重要,但可能有一种方法可以通过熊猫解决这个问题)。你知道吗
xls = ExcelFile('quiz/all_questions.xlsx')
df = xls.parse(xls.sheet_names[0], parse_cols = 241, keep_default_na=False, na_values=[""])
questions_2 = df.to_dict()
dict的当前结构如下:
{'id': {0: 'CB_1', 1: 'CB_2'}, 'question': {0: 'Who is Ghoulsbee Scroggins?', 1: 'Who is Ebeneezer Yakbain?}, 'choice1': {0: 'Cat', 1: 'A mathematician'}, 'choice2': {0: 'Dog', 1: 'A mathematician'}, 'choice3': {0: 'Ape: 'A mathematician'}, 'choice4': {0: 'Astrophysicist', 1: 'A mathematician'}, 'solution': {0: 'Ape', 1: 'A mathematician'}
我想把它变成一个有序的格言形式:
[OrderedDict([('id', '1'), ('question', 'What is the capital of China?'), ('choice1', 'Shanghai'), ('choice2', 'Guangzhou'), ('choice3', 'Hong Kong'), ('choice4', 'Beijing'), ('solution', 'Beijing')]), OrderedDict([('id', '2'), ('question', 'What year did World War 1 start?'), ('choice1', '1896'), ('choice2', '1914'), ('choice3', '1921'), ('choice4', '1929'), ('solution', '1914')]), OrderedDict([('id', '3'), ('question', 'What is the second closest planet to the sun?'), ('choice1', 'Saturn'), ('choice2', 'Mercury'), ('choice3', 'Venus'), ('choice4', 'Mars'), ('solution', 'Venus')]), OrderedDict([('id', '4'), ('question', 'What is the symbol for gold on the periodic table?'), ('choice1', 'Au'), ('choice2', 'Gd'), ('choice3', 'Gl'), ('choice4', 'Or'), ('solution', 'Au')])]
我似乎不知道如何以正确的顺序遍历键、值对来构造元组列表。有什么想法吗?你知道吗
一种解决方案是使用
OrderedDict
和for
循环。你知道吗结果
解释
OrderedDict
并将空列表定义为默认值的类。你知道吗id
。对于每个id
,将项添加到与给定列表order_or_keys
对齐的有序字典中。你知道吗OrderedDict
追加到结果列表。你知道吗有序字典会记住其内容的添加顺序,并跟踪顺序。如果不能控制插入顺序,可以通过以下方式重新排序:
另外,正如旁注一样,在Python3中,dictionary是有序的(虽然这是一个技术上不应该依赖的特性),因此您可以创建另一个dictionary并按所需的顺序插入项目,这比ordered dictionary更好,因为ordered dict在其中存储了一个链表来跟踪顺序,因此需要更多的内存。你知道吗
相关问题 更多 >
编程相关推荐