繁体   English   中英

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

[英]Update type of value in dictionary within list

有人可以启发我吗?:

我有一个字典列表:

[{'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'},
...]

非常感激。

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

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

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)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM