为了账号安全,请及时绑定邮箱和手机立即绑定

更新列表中字典中值的类型

更新列表中字典中值的类型

慕婉清6462132 2023-07-18 16:52:31
有人能告诉我这个吗?:我有一个字典列表:[{'overall': 5.0,  'vote': 'overall',  'reviewerID': 'AAP7PPBU72QFM'}, {'overall': 3.0,  'vote': '5',  'reviewerID': 'A2E168DTVGE6SV'},...]如何将“总体”和“投票”项转换为整数,同时将所有非有效数字设置为 0?更清楚地说,所需的输出是:[{'overall': 5,  'vote': 0,  'reviewerID': 'AAP7PPBU72QFM'}, {'overall': 3,  'vote': 5,  'reviewerID': 'A2E168DTVGE6SV'},...]非常感激。
查看完整描述

3 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

另一个解决方案很棒,这是可读性的另一个解决方案:


list_dicts = [{'overall': 5.0,

  'vote': 'overall',

  'reviewerID': 'AAP7PPBU72QFM'},

 {'overall': 3.0,

  'vote': '5',

  'reviewerID': 'A2E168DTVGE6SV'}]


def fix_key(d, k):

    try:

        d[k] = int(d[k])

    except:

        d[k] = 0


def fix(d):

    fix_key(d, 'vote')

    fix_key(d, 'overall')

    return d


list_dicts = [fix(d) for d in list_dicts]


# [{'overall': 5, 'vote': 0, 'reviewerID': 'AAP7PPBU72QFM'}, {'overall': 3, 'vote': 5, 'reviewerID': 'A2E168DTVGE6SV'}]

print(list_dicts)


查看完整回答
反对 回复 2023-07-18
?
长风秋雁

TA贡献1757条经验 获得超7个赞

def clean_value(x):

    try:

        return int(x)

    except ValueError:

        return 0


def clean_list_of_dicts(l):

    return [{

        k:v if k not in ('overall', 'vote') else clean_value(v) \

        for k, v in d.items()

    } for d in l]

对您的输入数据进行的测试表明该解决方案有效。


>>> clean_list_of_dicts([{'overall': 5.0,

  'vote': 'overall',

  'reviewerID': 'AAP7PPBU72QFM'},

 {'overall': 3.0,

  'vote': '5',

  'reviewerID': 'A2E168DTVGE6SV'}

])

给出输出:


[{'overall': 5,

  'vote': 0,

  'reviewerID': 'AAP7PPBU72QFM'},

 {'overall': 3,

  'vote': 5,

  'reviewerID': 'A2E168DTVGE6SV'}]


查看完整回答
反对 回复 2023-07-18
?
九州编程

TA贡献1785条经验 获得超4个赞

我希望它对你有用,但与函数一起使用会更好

for i in data:
  i['overall'] =int(i['overall'])
  i['vote'] = int(i['vote']) if (i['vote']).isdigit() else 0


查看完整回答
反对 回复 2023-07-18
  • 3 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信