Friday, 15 October 2021

partial string formatting

 s = '{foo} {bar}'

s.format(foo='FOO', bar='{bar}')


from: https://stackoverflow.com/questions/11283961/partial-string-formatting

Saturday, 9 October 2021

How to check if one dictionary is a subset of another larger dictionary?

 

In Python 3, you can use dict.items() to get a set-like view of the dict items. You can then use the <= operator to test if one view is a "subset" of the other:

d1.items() <= d2.items()

In Python 2.7, use the dict.viewitems() to do the same:

d1.viewitems() <= d2.viewitems()

In Python 2.6 and below you will need a different solution, such as using all():

all(key in d2 and d2[key] == d1[key] for key in d1)

 

from:  https://stackoverflow.com/questions/9323749/how-to-check-if-one-dictionary-is-a-subset-of-another-larger-dictionary

Friday, 1 October 2021

Sort JSON object using json.dumps()

 # Import the JSON module

import json

# Array of JSON Objects
products = [{"name": "HDD", "brand": "Samsung", "price": 100},
            {"name": "Monitor", "brand": "Dell", "price": 120},
            {"name": "Mouse", "brand": "Logitech", "price": 10}]

# Read and print the original data
print("The original data:\n{0}".format(products))
# Convert into the JSON object after sorting
sorted_json_data = json.dumps(products, sort_keys=True)
# Print the sorted JSON data
print("The sorted JSON data based on the keys:\n{0}".format(sorted_json_data))


from: https://linuxhint.com/sort-json-objects-python/

Thursday, 16 September 2021

How to convert Nonetype to int or string?

 int(value or 0)


from: https://stackoverflow.com/questions/3930188/how-to-convert-nonetype-to-int-or-string

how to dynamically create an instance of a class in python?

 all you will need to do is

klass = globals()["class_name"]
instance = klass()


from: https://stackoverflow.com/questions/3451779/how-to-dynamically-create-an-instance-of-a-class-in-python

Python mock multiple return values

Answer #1:

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'


from: https://www.py4u.net/discuss/16628 

Monday, 13 September 2021

Check if a given key already exists in a dictionary and increment it

 I prefer to do this in one line of code.

my_dict = {}

my_dict[some_key] = my_dict.get(some_key, 0) + 1


from: https://stackoverflow.com/questions/473099/check-if-a-given-key-already-exists-in-a-dictionary-and-increment-it