53 lines
1.0 KiB
Python
53 lines
1.0 KiB
Python
# # The get() method on dicts
|
|
# # and its "default" argument
|
|
#
|
|
# name_for_userid = {
|
|
# 382: "Alice",
|
|
# 590: "Bob",
|
|
# 951: "Dilbert",
|
|
# }
|
|
#
|
|
# def greeting(userid):
|
|
# return "Hi %s!" % name_for_userid.get(userid, "there")
|
|
#
|
|
# greeting(382)
|
|
# # "Hi Alice!"
|
|
#
|
|
# greeting(333333)
|
|
# #"Hi there!"
|
|
#
|
|
# # ___________________________________________________________________
|
|
#
|
|
# # How to sort a Python dict by value
|
|
# # (== get a representation sorted by value)
|
|
#
|
|
# xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
|
|
#
|
|
# sorted(xs.items(), key=lambda x: x[1])
|
|
# [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
|
|
#
|
|
# # Or:
|
|
#
|
|
# import operator
|
|
# sorted(xs.items(), key=operator.itemgetter(1))
|
|
# [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
|
|
#
|
|
# # ___________________________________________________________________
|
|
#
|
|
# # How to merge two dictionaries
|
|
# # in Python 3.5+
|
|
#
|
|
# x = {'a': 1, 'b': 2}
|
|
# y = {'b': 3, 'c': 4}
|
|
#
|
|
# z = {**x, **y}
|
|
#
|
|
# z
|
|
# #{'c': 4, 'a': 1, 'b': 3}
|
|
#
|
|
# # In Python 2.x you could
|
|
# # use this:
|
|
# z = dict(x, **y)
|
|
# z
|
|
# #{'a': 1, 'c': 4, 'b': 3}
|