Ich möchte ein Wörterbuch in Python erstellen. Alle Beispiele, die ich sehe, instanziieren jedoch ein Wörterbuch aus einer Liste usw. ..
Wie erstelle ich ein neues leeres Wörterbuch in Python?
Rufen Sie dict
ohne Parameter auf
new_dict = dict()
oder einfach schreiben
new_dict = {}
Du kannst das
x = {}
x['a'] = 1
Es ist auch hilfreich zu wissen, wie man ein voreingestelltes Wörterbuch schreibt:
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}
Fügt den Wert in das python Wörterbuch ein.
d = dict()
oder
d = {}
oder
import types
d = types.DictType.__new__(types.DictType, (), {})
Es gibt also zwei Möglichkeiten, ein Diktat zu erstellen:
my_dict = dict()
my_dict = {}
Von diesen beiden Optionen ist {}
jedoch effizienter als dict()
und darüber hinaus lesbar. PRÜFEN SIE HIER
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}