Creating a new dictionary in Python

后端 未结 7 2032
难免孤独
难免孤独 2020-11-29 15:17

I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . ..

How do I create a new empty diction

7条回答
  •  感情败类
    2020-11-29 15:32

    Knowing how to write a preset dictionary is useful to know as well:

    cmap =  {'US':'USA','GB':'Great Britain'}
    
    # Explicitly:
    # -----------
    def cxlate(country):
        try:
            ret = cmap[country]
        except KeyError:
            ret = '?'
        return ret
    
    present = 'US' # this one is in the dict
    missing = 'RU' # this one is not
    
    print cxlate(present) # == USA
    print cxlate(missing) # == ?
    
    # or, much more simply as suggested below:
    
    print cmap.get(present,'?') # == USA
    print cmap.get(missing,'?') # == ?
    
    # with country codes, you might prefer to return the original on failure:
    
    print cmap.get(present,present) # == USA
    print cmap.get(missing,missing) # == RU
    

提交回复
热议问题