In Python, using the os.environ variable is the easiest way to set environment variables
Using os.environ Variable
os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set ...
In Python, there are 3 ways to get key by value in dictionary.
Using keys Function
Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.
The following example:
#!...
In Python, there are 3 ways to return dictionary keys as a list.
Using keys Function
The dict.keys() function returns a view object that displays a list of all the keys in the dictionary in order of insertion.
See the following example:
#!/usr/...
In Python, there are 3 ways to check if a variable exists.
Using locals Function
The locals() function returns the dictionary of the current local symbol table.
#!/usr/bin/python3
vName = 1
if 'vName' in locals():
print("exists")
exists
...
In Python, there are 4 ways to copy a dictionary.
Using dict Method
If you want to copy the dict, you have to do so explicitly with:
#!/usr/bin/python3
a = {"a": 1, "b": 2}
# Copy
b = dict(a)
b['a'] = 3
print(a)
print(b)
{'a': 1, 'b': 2}
{'...
In Python, there are 3 ways to remove duplicates in list.
Using Built-in set Function
The built-in set() function returns a new set object, optionally with elements taken from iterable. If you later need a real list again, you can similarly pass the...
In Python, there are 2 ways to delete an item from a dictionary.
Using del Statement
The easiest way to delete an item from a dictionary in Python:
#!/usr/bin/python3
m = {"a":1, "b":2}
# remove a
if 'a' in m:
del m['a']
print(m)
{'b': 2...
In Python, there are 3 ways to count the occurrences of a list item.
Using count Method
The str.count() method returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpr...
In Python, there are 3 ways to merge two dictionaries into a new dictionary.
Using Additional Unpacking Generalizations
Starting with Python 3.5, we can merge in with literal notation as well. See the following example:
#!/usr/bin/python3
# -*-...
Converting Json to string in Python.Decoding JSON
To convert string to json in Python, use the json.loads() function. The json.loads() is a built-in Python function that accepts a valid json string and returns a dictionary to access all elements. The...
Check if a given key already exists in a dictionary.Using the in operator
In this method, we use the membership operator in. This operator is used to check if one value is a member of another. It returns a boolean value.
dict = {"GMT": 0, "BST": 1}
...