4 Years
Discussion Span
Last Post by vegaseat

In a nutshell ...
A dictionary is an unordered set of key:value pairs sometimes
called associative arrays, mappings or hash tables.

Dictionaries are indexed with unique keys instead of ordinal offset values.
Numbers and strings can always be used as keys and can be mixed.
Dictionaries grow or shrink on an as-needed basis.
A dictionary is not a sequence like a list or tuple.

Here is an example ...

# dictionary keys are in hash order to allow for fast lookup

# create an empty dictionary
ger_eng_dic = {}  # or ger_eng_dic = dict()

# add/load new key:value pairs by using indexing and assignment
# here 'eins' is the key, 'one' is the key value
# the start of a german to english dictionary
ger_eng_dic['null'] = 'zero'
ger_eng_dic['eins'] = 'one'
ger_eng_dic['zwei'] = 'two'
ger_eng_dic['drei'] = 'three'
ger_eng_dic['vier'] = 'four'

# print loaded dictionary
# the dictionary key order allows for most efficient searching
print("Dictionary now contains (notice the seemingly random order of keys):")
for key, val in ger_eng_dic.items():
    print("%s: %s" % (key, ger_eng_dic[key]))

print('-'*30)  # 30 dashes

# find the value by key (does not change dictionary)
#print("The english word for drei is %" % ger_eng_dic['drei'])
# better
if 'drei' in ger_eng_dic:
    print("The english word for drei is %s" % ger_eng_dic['drei'])

'''result ...
Dictionary now contains (notice the seemingly random order of keys):
eins: one
drei: three
vier: four
null: zero
zwei: two
The english word for drei is three

Edited by vegaseat

Votes + Comments
short and crisp!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.