如何获取嵌套在列表中的多个字典中键的最小值?

huangapple go评论68阅读模式
英文:

how to get the smallest value of a key in multiple dictionaries nested in a list?

问题

我有类似这样的东西

data = [{'name': 'abc', 'id': 'abc123','price': '$10'},
       {'name': 'def', 'id': 'efg123','price': '$15'},
       {'name': 'ghi', 'id': 'ghi123','price': '$5'}, ]

我想要做的是首先从所有字典的'price'键的值中删除'$'符号,然后比较所有字典中的值并打印其中最小的值。

我用以下方式去除符号

for i in data:
    data_price = i['price']
    new_price = data_price.strip('$')
    print(new_price)

但我不知道如何比较所有的值,然后获取最小的值,我还需要知道最小值属于哪个字典,因为我还需要它的'id'。

我该如何做呢?

英文:

I have something like this

data = [{'name': 'abc', 'id': 'abc123','price': '$10'},
       {'name': 'def', 'id': 'efg123','price': '$15'},
       {'name': 'ghi', 'id': 'ghi123','price': '$5'}, ]

what I want to do is first strip the '$' sign from the value of 'price' key from all the dictionaries and then compare the values in all the dictionaries and print the smallest one in them.

I did this for removing the symbol

for i in data:
    data_price = i['price']
    new_price = data_price.strip('$')
    print(new_price)

But I don't know how I compare all the values and then get the smallest one, and I also then need to know in which dictionary that smallest value belongs to because I also need its id.

how do I do that?

答案1

得分: 2

你可以按照以下方式获取它

```python
min_data = min(data, key=lambda dic: float(dic['price'].lstrip('$')))

使用for循环采用相同的方法,以简单的方式实现

def get_min(arr):
    store_min = {}
    for record in arr:
        val = float(record['price'].lstrip('$'))
        if val not in store_min:
            store_min[val] = []
        store_min[val].append(record)
    minimum_prices = store_min.keys()
    min_price = min(minimum_prices)
    return store_min[min_price][0] 
print(get_min(data))
# 输出 -> {'name': 'ghi', 'id': 'ghi123', 'price': '$5'}

<details>
<summary>英文:</summary>

you can get it as this 

min_data = min(data, key=lambda dic: float(dic['price'].lstrip('$')))


same approach with `for` loop in simple way

>>> def get_min(arr):
store_min = {}
for record in arr:
val = float(record['price'].lstrip('$'))
if val not in store_min:
store_min[val] = []
store_min[val].append(record)
minimum_prices = store_min.keys()
min_price = min(minimum_prices)
return store_minmin_price
print(get_min(data))

output -> {'name': 'ghi', 'id': 'ghi123', 'price': '$5'}


</details>



# 答案2
**得分**: 1

你可以使用[`min`][0]函数与一个关键函数:

```python
data = [{'name': 'abc', 'id': 'abc123', 'price': '$10'},
        {'name': 'def', 'id': 'efg123', 'price': '$15'},
        {'name': 'ghi', 'id': 'ghi123', 'price': '$5'}, ]

m = min(data, key=lambda d: int(d["price"][1:]))
# {'name': 'ghi', 'id': 'ghi123', 'price': '$5'}

请注意,你必须将price转换为数值类型,以便不会按字典顺序比较(例如,"10" < "5")。

英文:

You can use min with a key function:

data = [{&#39;name&#39;: &#39;abc&#39;, &#39;id&#39;: &#39;abc123&#39;,&#39;price&#39;: &#39;$10&#39;},
        {&#39;name&#39;: &#39;def&#39;, &#39;id&#39;: &#39;efg123&#39;,&#39;price&#39;: &#39;$15&#39;},
        {&#39;name&#39;: &#39;ghi&#39;, &#39;id&#39;: &#39;ghi123&#39;,&#39;price&#39;: &#39;$5&#39;}, ]


m = min(data, key=lambda d: int(d[&quot;price&quot;][1:]))
# {&#39;name&#39;: &#39;ghi&#39;, &#39;id&#39;: &#39;ghi123&#39;, &#39;price&#39;: &#39;$5&#39;}

Note that you have to cast price
to a numerical type, so that you won't compare lexicographically (where e.g. &quot;10&quot; &lt; &quot;5&quot;)

huangapple
  • 本文由 发表于 2023年3月7日 20:30:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定