title: How To Create a Unique Key For A Dictionary In Python
body: <p>What is the best way to generate a unique key for the contents of a dictionary. My intention is to store each dictionary in a document store along with a unique id or hash so that I don't have to load the whole dictionary from the store to check if it exists already or not. <em>Dictionaries with the same keys and values should generate the same id or hash.</em></p>
  
  <p>I have the following code:</p>
  
  <pre><code>import hashlib
  
  a={'name':'Danish', 'age':107}
  b={'age':107, 'name':'Danish'}
  
  print str(a)
  print hashlib.sha1(str(a)).hexdigest()
  print hashlib.sha1(str(b)).hexdigest()
  </code></pre>
  
  <p>The last two print statements generate the same string. Is this is a good implementation? or are there any pitfalls with this approach? Is there a better way to do this?</p>
  
  <p><strong>Update</strong></p>
  
  <p>Combining suggestions from the answers below, the following might be a good implementation</p>
  
  <pre><code>import hashlib
  
  a={'name':'Danish', 'age':107}
  b={'age':107, 'name':'Danish'}
  
  
  def get_id_for_dict(dict):
      unique_str = ''.join(["'%s':'%s';"%(key, val) for (key, val) in sorted(dict.items())])
      return hashlib.sha1(unique_str).hexdigest()
  
  print get_id_for_dict(a)
  print get_id_for_dict(b)
  </code></pre>