Pythonic way to check if two dictionaries have the identical set of keys?

前端 未结 6 2053
日久生厌
日久生厌 2020-12-14 15:50

For example, let\'s say I have to dictionaries:

d_1 = {\'peter\': 1, \'adam\': 2, \'david\': 3}

and

d_2 = {\'peter\': 14, \         


        
相关标签:
6条回答
  • 2020-12-14 15:59
    • In Python 3, dict.keys() returns a "view object" that can be used like a set. This is much more efficient than constructing a separate set.

      d_1.keys() == d_2.keys()
      
    • In Python 2.7, dict.viewkeys() does the same thing.

      d_1.viewkeys() == d_2.viewkeys()
      
    • In Python 2.6 and below, you have to construct a set of the keys of each dict.

      set(d_1) == set(d_2)
      

      Or you can iterate over the keys yourself for greater memory efficiency.

      len(d_1) == len(d_2) and all(k in d_2 for k in d_1)
      
    0 讨论(0)
  • 2020-12-14 16:01
    >>> not set(d_1).symmetric_difference(d_2)
    False
    >>> not set(d_1).symmetric_difference(dict.fromkeys(d_1))
    True
    
    0 讨论(0)
  • 2020-12-14 16:10

    You can get the keys for a dictionary with dict.keys().

    You can turn this into a set with set(dict.keys())

    You can compare sets with ==

    To sum up:

    set(d_1.keys()) == set(d_2.keys())
    

    will give you what you want.

    0 讨论(0)
  • 2020-12-14 16:15

    One way is to check for symmetric difference (new set with elements in either s or t but not both):

    set(d_1.keys()).symmetric_difference(set(d_2.keys()))
    

    But a shorter way it to just compare the sets:

    set(d_1) == set(d_2)
    
    0 讨论(0)
  • 2020-12-14 16:19

    A quick option (not sure if its the most optimal)

    len(set(d_1.keys()).difference(d_2.keys())) == 0
    
    0 讨论(0)
  • 2020-12-14 16:23

    In Python2,

    set(d_1) == set(d_2)
    

    In Python3, you can do this which may be a tiny bit more efficient than creating sets

    d1.keys() == d2.keys()
    

    although the Python2 way would work too

    0 讨论(0)
提交回复
热议问题