Я хочу построить словарь на Python. Тем не менее, все примеры, которые я вижу, - создание словаря из списка и т. Д. ..
Как мне создать новый пустой словарь в Python?
Вызов dict без параметров
dict
new_dict = dict()
или просто напишите
new_dict = {}
Вы можете сделать это
x = {} x['a'] = 1
Полезно также знать, как написать предустановленный словарь:
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
>>> dict(a=2,b=4) {'a': 2, 'b': 4}
Добавит значение в словарь Python.
d = dict()
или
d = {}
import types d = types.DictType.__new__(types.DictType, (), {})
Итак, есть 2 способа создать диктовку:
my_dict = dict()
my_dict = {}
Но из этих двух вариантов {} эффективнее, чем dict() плюс его читабельность. ПРОВЕРИТЬ ЗДЕСЬ
{}
dict()
>>> dict.fromkeys(['a','b','c'],[1,2,3]) {'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}