更改 Python 字典中的键

Changing keys in Python dictionary

我正在尝试编写一个脚本,该脚本获取字典中的键并将它们替换为它们映射到 CSV 文件中的值。我在尝试查找匹配行时遇到问题。

CSV 文件

QuestionKey,QuestionId
BASIC1,F4AB5C41-5BB2-41BD-AF7C-08E76BA05DCE
BASIC2,1E6D5B13-BDD2-43E7-9B74-36AD8C816A9C

脚本:

QUESTIONS_MAP = pd.read_csv('data/question_ids.csv', dtype=str)

def replace_questions_ids_with_keys(content: dict) -> dict:
    """Replace the question ids with the keys used in the decision response"""
    # LOGGER.info(QUESTIONS_MAP)
    for key, value in content.items():
        # LOGGER.info(QUESTIONS_MAP.QuestionId)
        # Find item QuestionKey for item in QUESTIONS_MAP where key in QuestionId
        question_key = list(filter(lambda x: key in x['QuestionId'], QUESTIONS_MAP))
        LOGGER.info(question_key)
        if question_key:
            content[QUESTIONS_MAP[key]] = value
            del content[key]
    return content

示例content 字典:

{'F4AB5C41-5BB2-41BD-AF7C-08E76BA05DCE': '', '1E6D5B13-BDD2-43E7-9B74-36AD8C816A9C': ''}

运行时错误:

2022-05-18 14:46:55,340 -  ERROR - string indices must be integers

预期响应:

{'BASIC1': '', 'BASIC2': ''}

首先,使用字典比使用数据框更方便。因此,

# map question id -> question key
# squeeze tells pandas to produce a series when there's only one column
# index=1 tells it to use question id as an index
# finally, .to_dict() makes a dictionary out of the series
QUESTIONS_MAP = pd.read_csv('filename.csv', squeeze=True, index_col=1).to_dict()

然后,使用字典理解:

content = {
    QUESTIONS_MAP[id_]: value 
    for id_, value in content.items() 
    if id_ in QUESTIONS_MAP
}

恕我直言,我认为使用数据框(和 pandas)对于我所看到的来说有点矫枉过正。

这是一个简单的解决方案:

import pandas as pd

QUESTIONS_MAP = pd.read_csv('data/question_ids.csv', dtype=str)

def replace_questions_ids_with_keys(content: dict) -> dict:
    """Replace the question ids with the keys used in the decision response"""
    result = {}
    for key, value in content.items():
        for i in range(len(QUESTIONS_MAP)):
            question_key = QUESTIONS_MAP.values[i][0]
            question_id = QUESTIONS_MAP.values[i][1]
            if question_id == key:
                result[question_key] = ""
    return result

my_dict = {'F4AB5C41-5BB2-41BD-AF7C-08E76BA05DCE': '', '1E6D5B13-BDD2-43E7-9B74-36AD8C816A9C': ''}


replace_questions_ids_with_keys(my_dict)