检查每个相似键的每个值是否满足2 dict - PYTHON中每个键的条件



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

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个"使1 "ABBB"

非常感谢你的帮助。

谢谢!

如果您知道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')

最新更新