简体   繁体   English

如何更改列表中字典中特定键的值类型?

[英]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.

相关问题 如何将字典中的列表更改为键和他的值? - How can I change a list in a dictionary into a key and he's value? 如何从包含键作为字典列表的字典中获取第一个键值对(即“类型”:45) - How do i fetch first key value pair (i.e., 'type': 45) from a dictionary which contains key as list with dictionaries 如何使列表成为字典中的键值? - How do I make a list a key value in a dictionary? 如何按键长度对字典进行排序,然后按值列表中的元素排序? - How do I sort a dictionary by key length, then by an element in the value list? 如何使用列表的元素来设置字典的键和值? - How do I use elements of list to set the key and value of dictionary? 如何判断字典中特定键的值是否是字典,以便我可以基于此递归解决编程问题? - How do I tell if the value of a particular key in my dictionary is a dictionary so that I can solve programming questions based on this recursively? 解耦包含列表作为特定键的值的字典 - Decouple dictionary that contains a list as a value for a particular key 如何使用python从列表中获取字典,将列表条目作为键,并将列表中的项数作为值? - How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python? 如何将列表列表更改为键值? - How do I change a list of lists to key, value? django视图中的函数返回字典列表。 如何在其机器人测试用例中获取特定键的价值 - A function in django view returns a list of dictionary. How can I get value to particular key in its robot test case
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM