Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. base_config = {'key1': 'val1'}
  2.  
  3. func1(base_config + {'key2': 'val2'})
  4. func2(base_config + {'key3': 'val3'})
  5.  
  6. Explicit is better than implicit.
  7. In the face of ambiguity, refuse the temptation to guess.
  8. There should be one-- and preferably only one --obvious way to do it.
  9.  
  10. result = {'a': 1, 'b': 2} + {'a': 3, 'c': 0}
  11.  
  12. result = {'a': 3, 'b': 2, 'c': 0}
  13.  
  14. def dict_add_keep_last(a, b): # aka merged() or updated()
  15. d = a.copy()
  16. d.update(b)
  17. return d
  18.  
  19. result = dict(a, **b) # результат тот же
  20.  
  21. result = {**a, **b}
  22.  
  23. result = {**b, **a} # Python 3.5, or else swap a, b: dict_add_keep_last(b, a)
  24.  
  25. >>> from collections import Counter
  26. >>> Counter(a) + Counter(b)
  27. Counter({'a': 4, 'b': 2})
  28.  
  29. result = {'a': [1, 3], 'b': 2, 'c': 0}
  30.  
  31. >>> from decimal import Decimal
  32. >>> a = 1
  33. >>> a += Decimal(2)
  34. >>> a
  35. Decimal('3')
  36.  
  37. for it in [b, c, d, ..]:
  38. a.update(it)
  39.  
  40. try:
  41. from collections import ChainMap
  42. except ImportError: # Python 2
  43. from ConfigParser import _Chainmap as ChainMap
  44.  
  45. import itertools
  46. base_config = {'key1': 'val1'}
  47.  
  48. func1(dict(itertools.chain(base_config.iteritems(), {'key2': 'val2'}.iteritems())))
  49. func2(dict(itertools.chain(base_config.iteritems(), {'key3': 'val3'}.iteritems())))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement