使用指定的Ord将字典转换为有序字典

2024-09-27 00:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一本有六个键的字典,这些键的理想顺序如下:

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')])]

我似乎不知道如何以正确的顺序遍历键、值对来构造元组列表。有什么想法吗?你知道吗


Tags: theid字典顺序isxlswhatordereddict
2条回答

一种解决方案是使用OrderedDictfor循环。你知道吗

from collections import OrderedDict

order_of_keys = ["id", "question", "choice1", "choice2", "choice3", "choice4", "solution"]

input_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', 1: 'A mathematician'},
              'choice4': {0: 'Astrophysicist', 1: 'A mathematician'},
              'solution': {0: 'Ape', 1: 'A mathematician'}}

res = []

for key in input_dict['id']:
    d = OrderedDict()
    d['id'] = key
    for k in order_of_keys[1:]:
        d[k] = input_dict[k][key]
    res.append(d)

结果

[OrderedDict([('id', 0),
              ('question', 'Who is Ghoulsbee Scroggins?'),
              ('choice1', 'Cat'),
              ('choice2', 'Dog'),
              ('choice3', 'Ape'),
              ('choice4', 'Astrophysicist'),
              ('solution', 'Ape')]),
 OrderedDict([('id', 1),
              ('question', 'Who is Ebeneezer Yakbain?'),
              ('choice1', 'A mathematician'),
              ('choice2', 'A mathematician'),
              ('choice3', 'A mathematician'),
              ('choice4', 'A mathematician'),
              ('solution', 'A mathematician')])]

解释

  • 创建一个子类OrderedDict并将空列表定义为默认值的类。你知道吗
  • 循环通过每个id。对于每个id,将项添加到与给定列表order_or_keys对齐的有序字典中。你知道吗
  • 将每个OrderedDict追加到结果列表。你知道吗

有序字典会记住其内容的添加顺序,并跟踪顺序。如果不能控制插入顺序,可以通过以下方式重新排序:

# od is your ordered dictionary

for key in reversed(order_of_keys):
    od.move_to_end(key)

另外,正如旁注一样,在Python3中,dictionary是有序的(虽然这是一个技术上不应该依赖的特性),因此您可以创建另一个dictionary并按所需的顺序插入项目,这比ordered dictionary更好,因为ordered dict在其中存储了一个链表来跟踪顺序,因此需要更多的内存。你知道吗

相关问题 更多 >

    热门问题