Intersecting two dictionaries in Python

后端 未结 8 2048
借酒劲吻你
借酒劲吻你 2020-11-27 18:26

I am working on a search program over an inverted index. The index itself is a dictionary whose keys are terms and whose values are themselves dictionaries of short document

8条回答
  •  抹茶落季
    2020-11-27 18:36

    In Python, you use the & operator to calculate the intersection of sets, and dictionary keys are set-like objects (in Python 3):

    dict_a = {"a": 1, "b": 2}
    dict_b = {"a": 2, "c": 3} 
    
    intersection = dict_a.keys() & dict_b.keys()  # {'a'}
    

    On Python 2 you have to convert the dictionary keys to sets yourself:

    keys_a = set(dict_a.keys())
    keys_b = set(dict_b.keys())
    intersection = keys_a & keys_b
    

提交回复
热议问题