遍历字典列表时无法转换数据类型

时间:2019-04-03 11:46:37

标签: 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)

2 个答案:

答案 0 :(得分:4)

这是执行此操作的版本:

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


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

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

答案 1 :(得分:1)

尝试这种方法:

New_List = []
for dictionary in top_rank_data:
    Sub_Dict = {}
    for key, value in dictionary.items():
        Type = search_results_config[key]
        try:
            New_Val = Type(value)
        except:
            New_Val = value

        Sub_Dict[key] = New_Val

    New_List.append(Sub_Dict)