[英]How do I change the value type of a particular key in a dictionary in a list?
list = [
{'rank': '1', 'name': 'Gus’s World Famous Fried Chicken', 'stars': '4.0', 'numrevs': '549', 'price': '$$'},
{'rank': '2', 'name': 'South City Kitchen - Midtown', 'stars': '4.5', 'numrevs': '1777', 'price': '$$'}
]
I need to update numrevs
to int
.我需要将
numrevs
更新为int
。
I have this so far, but I can't get it to work:到目前为止我有这个,但我无法让它工作:
list = [dt.update({k : int(v)}) for dt in rankings for k['numrevs'], v in dt.items()]
Basically you can do it quite easy with that:基本上你可以很容易地做到这一点:
for d in mylist:
d["numrevs"] = int(d["numrevs"])
As a remark: Don't name any variable list
.备注:不要命名任何变量
list
。 list
is a built-in function and to overwrite this function can only lead to problems therefore I renamed the list to mylist
. list
是一个内置函数,覆盖这个函数只会导致问题,因此我将 list 重命名为mylist
。
For each dict in your list, create a new dict, where the value for each key is the same as the current dict, except for the values that you want to replace with an int.对于列表中的每个 dict,创建一个新的 dict,其中每个键的值与当前的 dict 相同,除了要替换为 int 的值。
Here I am calling the current list list1
to avoid the confusion between the variable name and the built-in type name.这里我调用当前列表
list1
为了避免变量名和内置类型名的混淆。
list2 = [ {k:(int(v) if k=='numrevs' else v)
for k,v in d.items()}
for d in list1 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.