首页 文章

在Python中创建一个新的dict

提问于
浏览
330

我想用Python构建一个字典 . 但是,我看到的所有示例都是从列表中实例化字典等 . ..

如何在Python中创建一个新的空字典?

7 回答

  • 3
    d = dict()
    

    要么

    d = {}
    

    要么

    import types
    d = types.DictType.__new__(types.DictType, (), {})
    
  • 13

    所以有两种方法可以创建一个dict:

    • my_dict = dict()

    • my_dict = {}

    但是在这两个选项中, {}dict() 更有效 . CHECK HERE

  • 1

    你可以这样做

    x = {}
    x['a'] = 1
    
  • 180
    >>> dict.fromkeys(['a','b','c'],[1,2,3])
    
    
    {'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
    
  • 490

    知道如何编写预设字典也很有用:

    cmap =  {'US':'USA','GB':'Great Britain'}
    
    def cxlate(country):
        try:
            ret = cmap[country]
        except:
            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
    
  • 20
    >>> dict(a=2,b=4)
    {'a': 2, 'b': 4}
    

    将在python字典中添加值 .

  • 12

    不带参数调用 dict

    new_dict = dict()
    

    或者简单地写

    new_dict = {}
    

相关问题