标签:slist bit ret lis index mis brunch rar tor
Python Dictionaries are
in dictionaries, items are stored and fetched by key.
'''Basic Dictionary Operations'''
D = {'spam': 2, 'ham': 1, 'eggs': 3} # dict in literal expression
# key indexing support fetch, add, change, delete
print(D['spam']) # fetch a value by key
D['brunch'] = 'Bacon' # add new entry
D['ham'] = ['grill', 'bake', 'fry'] # change entry
del D['egg'] # delete entry
print(D)
'''
2
{'brunch': 'Bacon', 'spam': 2, 'ham': ['grill', 'bake', 'fry']}
'''
'''Dictionary Methods'''
D = {'spam': 2, 'ham': 1, 'eggs': 3}
# d.keys(), d.values(), d.items()
# useful in loops that need to step through dictionary entries one by one
for element in [D.keys(),
D.values(),
D.items()]: # (key,value) pair tuples
print(list(element))
# d.get(key[, default])
print(
D.get('spam'),
D.get('toast'), # a key that is missing
D.get('toast', 88),
'\n',
end=""
)
# d.update([other])
D2 = {'toast':4, 'muffin':5} # would overwrite values of the same key if there’s a clash
D.update(D2)
print(D)
# d.pop(key[, default])
# deletes a key from a dictionary and returns the value it had
print(
D.pop('muffin'),
D.pop('toast'),
D
)
'''
['spam', 'ham', 'eggs']
[2, 1, 3]
[('spam', 2), ('ham', 1), ('eggs', 3)]
2 None 88
{'spam': 2, 'ham': 1, 'eggs': 3, 'toast': 4, 'muffin': 5}
5 4 {'spam': 2, 'ham': 1, 'eggs': 3}
'''
'''Other Ways to Make Dictionaries'''
# -------two basic forms------- #
a = {'one': 1, 'two': 2, 'three': 3} # literal expression
b = {} # assign by keys dynamically
b['one'] = 1
b['two'] = 2
b['three'] = 3
# -------dict constructor------- #
# dict(**kwarg)
c = dict(one=1, two=2, three=3) # requires all keys to be strings
# dict(mapping, **kwarg)
d = dict({'three': 3, 'one': 1, 'two': 2})
# dict(iterable, **kwarg)
e = dict([('two', 2), ('one', 1)], three = 3)
keyslist = ['one', 'two', 'three']
valueslist = [1, 2, 3]
zipObject = zip(keyslist, valueslist) # first use zip() to construct iterable
# print(list(zipObject))
f = dict(zipObject)
# -------dictionary comprehension expression------- #
g = {k:v for (k, v) in zip(keyslist, valueslist)} # iterable object can only be iterated once
print(a==b==c==d==e==f==g)
'''
True
'''
标签:slist bit ret lis index mis brunch rar tor
原文地址:https://www.cnblogs.com/bit-happens/p/11869860.html