python - 循环字典列表时无法转换数据类型

标签 python python-3.x

我正在尝试循环遍历字典列表,并根据对另一个配置字典的引用来转换它们的数据类型,该配置字典包含我想要转换为的数据类型。

配置字典如下:

search_results_config = {

    'id':'int',
    'description':'string',
    'page':'int',
    'position':'int',
    'title':'string',
    'type':'int',
    'typedescription':'string',
    'url':'string'
}

我实际上尝试循环遍历 top_rank_data 并更改其数据类型的字典列表如下所示:

 {
        'description': 'Churchill contents insurance covers the things that matter most in your home. We offer cover of up to £50,000 as\xa0',
        'position': 18, 'page': 2, 'title': 'Contents insurance | Home Insurance | Churchill UK', 'type': '0',
        'typedescription': 'organic', 'url': 'https://www.churchill.com/home-insurance/options/contents'}, {
        'description': 'Compare contents insurance and how to cut the cost of home contents insurance cover for your personal possessions\xa0',
        'position': 19, 'page': 2, 'title': 'Contents Insurance - compare cheap contents insurance', 'type': '0',
        'typedescription': 'organic', 'url': 'https://www.uswitch.com/home-insurance/contents-insurance/'}

下面的代码是:

for row in top_rank_data:

    for item in row:

        for key, value in search_results_config.items():
            new_value = None
            config_type = search_results_config[key]

        if config_type == 'string':
            new_value = str(value) or ''

        if config_type == 'int':
            new_value = int(value) or 9

因此,我希望任何键的值都会根据 search_results_config 字典更改数据类型。相反,我只返回所有的 string 数据类型,因此我认为 if config_type 语句不起作用。非常感谢任何帮助!

生成数据的附加函数:

path = 'C:\downloaded'
for filename in glob.glob(os.path.join(path, '*.json')):
    with open(filename, encoding='utf-8', mode='r') as currentFile:
        data = currentFile.read()
        rank_data = json.loads(data)["rankdata"]

        for entry in rank_data:
            if (entry["page"]) <= 2 and (entry["typedescription"]) == "organic":
                top_rank_data.append(entry)

最佳答案

这是一个可以做到这一点的版本:

search_results_config = {

    'id': int,
    'description': str,
    'page': int,
    'position': int,
    'title': str,
    'type': int,
    'typedescription': str,
    'url': str
}

items = ({
        'description': 'Churchill contents insurance covers the things that matter most in your home. We offer cover of up to £50,000 as\xa0',
        'position': 18, 'page': 2, 'title': 'Contents insurance | Home Insurance | Churchill UK', 'type': '0',
        'typedescription': 'organic', 'url': 'https://www.churchill.com/home-insurance/options/contents'}, {
        'description': 'Compare contents insurance and how to cut the cost of home contents insurance cover for your personal possessions\xa0',
        'position': 19, 'page': 2, 'title': 'Contents Insurance - compare cheap contents insurance', 'type': '0',
        'typedescription': 'organic', 'url': 'https://www.uswitch.com/home-insurance/contents-insurance/'})

def convert(dct):
    return {key: search_results_config[key](value) for key, value in dct.items()}


for dct in items:
    print(convert(dct))

请注意,search_results_config 直接包含用于转换数据的类型(即 int 而不是 'int')。


您还可以为 search_results_config 中不存在的 key 添加默认类型(我在下面的示例中使用了 str):

def convert(dct):
    return {key: search_results_config.get(key, str)(value) 
            for key, value in dct.items()}

关于python - 循环字典列表时无法转换数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55494405/

相关文章:

python - 如何将日期时间格式转换为分钟 - pandas

Django:从一个 View 创建多个对象

python - 如何使用 Python 在 MySQL 数据库中存储 API 响应?

python - 带条件的 Pandas DF 中的一系列算术 - 先前的操作被覆盖

python - 在 Hadoop Streaming 作业中写入 Parquet 输出

python - 从 tiddlywiki 列表传递到 python 列表

python - 机器人框架无法识别某些类关键字

python - 递归错误 : maximum recursion depth exceeded in comparison

python - Google 应用引擎上的 Django : "Instance names cannot contain the ' :' character."

Python 请求 422 post 错误