# Teach you three Python Programming Tips

2022-02-02 03:58:25

Share today 3 individual Python Programming tips , Let's see if you've ever used ？

## 1、 How to sort according to the size of dictionary values

We know , The essence of a dictionary is a hash table , It can't be sorted by itself , but Python 3.6 after , Dictionaries can be traversed in the order of insertion , This is the ordered dictionary , The principle is , You can read Why? Python3.6 After that, the dictionary is in order .

Knowing that , It's easy to do. , First sort the list with the key values of the dictionary , Then re insert the new dictionary , In this way, the new dictionary can traverse the output according to the size of the value . The code is as follows ：

``````>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> for k,v in xs.items():# Ergodic dictionary
...     print(k,v)
...
a 4
b 3
c 2
d 1
>>> new_order = sorted(xs.items(), key=lambda x: x) # Sort the list of key values of the dictionary

>>> new_xs = { k : v for k,v in new_order} # Insert a new dictionary into the ordered list
>>> new_xs
{'d': 1, 'c': 2, 'b': 3, 'a': 4}
>>> for k,v in new_xs.items(): ## The output of the new dictionary is ordered
...     print(k,v)
...
d 1
c 2
b 3
a 4
Copy code `````` Sort the list , You can also use the following methods ：

``````>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Copy code `````` ## 2、 Elegant one-time judgment of multiple conditions

If there are three conditions , As long as one is true, you can pass , Maybe you'll write ：

``````x, y, z = 0, 1, 0

if x == 1 or y == 1 or z == 1:
print('passed')
Copy code `````` actually , The following three methods are more Pythonic

``````if 1 in (x, y, z):
print('passed')

if x or y or z:
print('passed')

if any((x, y, z)):
print('passed')
Copy code `````` The last one uses Python Built in method  `any()`,any Accept an iteratable object as a parameter , Such as lists or tuples , As long as one of them is true , be  `any()`  Method returns true , Usage examples are as follows ：

``````>>> any(['a',(2,4),3,True])
True
>>> any(['a',(2,4),3,False])
True
>>> any(['a',(),3,False])
True
>>> any(['',(),0,False])
False
>>> any(('a',(),3,False))
True
>>> any(('',(),0,False))
False
##  Note that an empty iteratable object returns  False
>>> any(())
False
>>> any([])
False
>>> any('')
False
>>> any({})
False
Copy code `````` And  `any()`  Corresponding , That's the way.  `all()`, Only all are true , Only true , Note that empty iteratable objects always return true .

``````>>> all(['a',(2,4),1,True]) //list All for " really "
True
>>> all(['a',(),1,True])   //list Empty in element tuple
False
>>> all(['a',(2,4),0,True])
False
>>> all(['a',(2,4),3,False])
False

##  Note that an empty iteratable object returns  True
>>>all([])
True
>>> all(())
True
>>> all({})
True
>>> all('')
True
Copy code `````` View help documents , You can enter... In the interpreter help:

``````>>> help(all)
Help on built-in function all in module __builtin__:

all(...)
all(iterable) -> bool

Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
Copy code `````` ## 3、 How to merge two dictionaries gracefully

Operators can unpack dictionaries , This is very useful when merging dictionaries , such as ：

``````>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}

>>> z
{'c': 4, 'a': 1, 'b': 3}
Copy code `````` If in Python2.x in , It needs to be done ：

``````>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}
Copy code `````` Okay , My sharing is over . If other partners have better tips . Welcome to discuss in the comments ！