जवाबों:
dictकोई मापदंडों के साथ कॉल करें
new_dict = dict()
या बस लिखो
new_dict = {}
{}के ऊपर dict()के लिए और 5 बार []से अधिक list()।
कैसे एक पूर्व निर्धारित शब्दकोश लिखने के लिए जानने के रूप में अच्छी तरह से जानने के लिए उपयोगी है:
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
cxlateआपके उत्तर के साथ बिट भी जटिल लगता है। मैं सिर्फ इनिशियलाइज़ेशन पार्ट रखूँगा। ( cxlateअपने आप में बहुत जटिल है। आप बस return cmap.get(country, '?')।)
KeyErrorसे एक नंगे को छोड़कर पकड़ना चाहिए (जो चीजों को पकड़ लेगा जैसे KeyboardInterruptऔर SystemExit)।
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
अजगर शब्दकोश में मूल्य जोड़ देगा।
d = dict()
या
d = {}
या
import types
d = types.DictType.__new__(types.DictType, (), {})
तो वहाँ एक तानाशाही बनाने के 2 तरीके हैं:
my_dict = dict()
my_dict = {}
लेकिन इन दो विकल्पों {}में से dict()इसके पठनीय से अधिक कुशल है ।
यहा जांचिये
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}