Accessing dictionary of dictionary in python

后端 未结 7 512
醉梦人生
醉梦人生 2021-01-22 09:47

Hi in my code there is a dictionary of dictionary.

nrec={\'bridge\': \'xapi1\', \'current_operations\': {}, \'uuid\': \'9ae5ca7d-e7d6-7a81-f619-d0ea33efb534\', \         


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-01-22 10:18

    Your best bet to avoid exception is either try .. except, or use dictionary built-in methods.

    my_dict = {'one': {'two': 'hello world!'}, 'four': 'Dummy!'}
    try:
      my_name = my_dict['one']['two']
    except:
      pass
      // instead of pass, you can also return something or do something else
    
    try:
      my_dict['one']['two']
    except Exception as e:
      my_name = 'default'
      return my_name, e  // returns a tuple which contains 'default' and error message
    
    
    #or use has_key()
    
    # this is for one-level nested dictionary
    for id, items in my_dict.iteritems():
         if items.has_key('two'):
              //do something
    
    # or simply this  --> eliminates dummy for loop
    if my_dict['one'].has_key('two'):      // has_key returns True / False
          // do something
    
    # or use in operator  (replace has_key)
    if 'two' in my_dict['one'].keys():
         // do something
    
    
    # or get method
    
    my_dict['one'].get('two', 'Default')
    

    Get is nice if that's all you need to avoid exception.

提交回复
热议问题