python 如何从字典1中删除基于公共键的字典2中没有的键值?

ua4mk5z4  于 2022-11-27  发布在  Python
关注(0)|答案(3)|浏览(162)

我有两个大字典和两个字典有相同的关键字,(图像名称)和不同的值。
第一个名为train_descriptions的法令如下所示:

{'15970.jpg': 'Turtle Check Men Navy Blue Shirt',
 '39386.jpg': 'Peter England Men Party Blue Jeans',
 '59263.jpg': 'Titan Women Silver Watch',
 ....
 ....
 '1855.jpg': 'Inkfruit Mens Chain Reaction T-shirt'}

以及名为train_features的第二个dict

{'31973.jpg': array([[0.00125694, 0.        , 0.03409385, ..., 0.00434341, 0.00728011,
         0.01451511]], dtype=float32),
 '30778.jpg': array([[0.0174035 , 0.04345186, 0.00772929, ..., 0.02230316, 0.        ,
         0.03104496]], dtype=float32),
 ...,
 ...,

 '38246.jpg': array([[0.00403965, 0.03701203, 0.02616892, ..., 0.02296285, 0.00930257,
         0.04575242]], dtype=float32)}

这两部词典的篇幅如下:
len(train_descriptions)为44424,而len(train_features)为44441
如您所见,train_description字典的长度小于train_features字典的长度。train_features字典的键值比train_descriptions字典的键值多。如何从train_features字典中删除不在train_description字典中的键值?使它们的长度相同。

41zrol4v

41zrol4v1#

使用xor获取字典之间的差异

diff = train_features.keys() ^ train_descriptions.keys()
for k in diff:
    del train_features[k]
kq4fsx7k

kq4fsx7k2#

使用for loop

feat = train_features.keys()
desc = train_description.keys()
common = list(i for i in feat if i not in decc)

for i in common: del train_features[i]

编辑:见下文
上面的代码可以工作。但是我们可以通过不将dict_keys转换为list来更有效地完成这一点,如下所示:

for i in train_features.keys() - train_description.keys(): del train_features[i]

当python dict_keys被减去时,它会给出不常用键的dict_keys。第一个代码首先被转换成列表,这既不高效也不必要。

csga3l58

csga3l583#

如果在另一个dict中不存在,则仅pop()

for key in train_descriptions.keys():
    if key not in train_features.keys():
        train_features.pop(key)

相关问题