【问题标题】:Check every value for each similar keys whether it meets the condition for each key in 2 dict - PYTHON检查每个相似键的每个值是否满足 2 dict - PYTHON 中每个键的条件
【发布时间】:2021-03-04 05:03:47
【问题描述】:

我在 2 个字典中有这些数据。

dict1 = {"A":2, "B": 2, "C":2}
dict2 = {"A":2, "B":100, "C":100)

我检查每个键的值是否 dict1 中的值大于 dict2 中的值。 示例:

if dict1["A"]>=dict2["A"]:
   print("There are enough A parts")
if dict1["B"]>=dict2["B"]:
   print("There are enough B parts")

有没有办法让我检查两个字典之间的所有值而不必执行上述操作? 为了更好地理解它是这样的:

dict1={}
dict2 = {"A":2, "B":100, "C":100}
productID= "ABBB" #productID
quantityInput = 100
quantityToMake = productID*quantityInput #results in ABBB x100 times

 *** PROGRAM RUNS through each letter and update how many A and Bs are there and updates dict1

我被困在这里了。条件是,如果我有足够的部分,即 A、B、C、D,如上述情况, 我有足够的“A”来制作 2 个“ABBB”。

如果我们有每个键的 dict2 值如下:

dict2 = {"A":100, "B":2, "C":100}

我没有足够的 B 来制作 1 个“ABBB”,因为我们需要 3 个“B”来制作 1 个“ABBB”。

非常感谢您的帮助。对python很陌生。

谢谢!

【问题讨论】:

  • 我认为这个if dict1["A"]>=dict2["A"]:的比较应该是相反的if dict1["A"]<=dict2["A"]:if dict2["A"]>=dict1["A"]:

标签: python dictionary compare


【解决方案1】:

如果您知道dict2dict1 具有所有相同的键,则可以循环遍历dict1 的键并比较每个值:

In [20]: dict1 = {"A":2, "B": 2, "C":2, "D":4}
    ...: dict2 = {"A":2, "B":100, "C":100, "D":2}

In [21]: for k, v in dict1.items():
    ...:     if v >= dict2[k]:
    ...:         print(f"There are enough {k} parts")
    ...:
There are enough A parts
There are enough D parts

如果您实际上是在尝试处理表格数据,您也可以考虑使用pandas,因为它使很多此类比较和更新变得相当容易:

In [22]: import pandas as pd

In [23]: df = pd.DataFrame([dict1, dict2]).T

In [24]: df
Out[24]:
   0    1
A  2    2
B  2  100
C  2  100
D  4    2

In [25]: df.index[df[0].ge(df[1])]
Out[25]: Index(['A', 'D'], dtype='object')

【讨论】:

  • 感谢您的帮助!我需要询问另一层。如果假设我想根据 dict1 和 dict2 输出我可以制作的“ABBB”的数量,我该怎么做?例如,根据我上面的问题,给定 dict2 的第一个场景,我可以制作 2 个“ABBB”,而给定 dict2 的第二个场景,我不能制作任何“ABBB”。
猜你喜欢
  • 2023-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 2021-12-15
  • 1970-01-01
  • 2022-01-02
  • 2023-04-02
相关资源
最近更新 更多