Serialize Python Dictionary to String and Back

Arjun Thakur
Updated on 05-Mar-2020 06:48:18

962 Views

The JSON module is a very reliable library to serialize a Python dictionary into a string, and then back to a dictionary. The dumps function converts the dict to a string. exampleimport json my_dict = {    'foo': 42,    'bar': {       'baz': "Hello",       'poo': 124.2    } } my_json = json.dumps(my_dict) print(my_json)OutputThis will give the output −'{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'The loads function converts the string back to a dict. exampleimport json my_str = '{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}' my_dict = json.loads(my_str) print(my_dict['bar']['baz'])OutputThis will give the output −Hello

Compare Two Tuples in Python

Lakshmi Srinivas
Updated on 05-Mar-2020 05:57:34

6K+ Views

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on. example>>> a = (1, 2, 3) >>> b = (1, 2, 5) >>> a < b TrueThere is another type of comparison that takes into account similar and different elements. This can be performed using sets. Sets will take the tuples and take only unique values. Then you can perform a & operation that ... Read More

Grep a Particular Keyword from Python Tuple

Lakshmi Srinivas
Updated on 05-Mar-2020 05:54:11

230 Views

If you have a tuple of strings and you want to search for a particular string, You can use the in operator. exampletpl = ("Hello", "world", "Foo", "bar") print("world" in tpl)OutputThis will give the output −TrueExampleIf you want to check if there is a substring present. You can loop over the tuple and find it using:tpl = ("Hello", "world", "Foo", "bar") for i in tpl:    if "orld" in i:       print("Found orld in " + i )OutputThis will give the output −Found orld in world

Convert Bytes Array to JSON Format in Python

Arjun Thakur
Updated on 05-Mar-2020 05:44:42

19K+ Views

You need to decode the bytes object to produce a string. This can be done using the decode function from string class that will accept then encoding you want to decode with. examplemy_str = b"Hello" # b means its a byte string new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding print(new_str)OutputThis will give the outputHelloOnce you have the bytes as a string, you can use the JSON.dumps method to convert the string object to JSON. examplemy_str = b'{"foo": 42}' # b means its a byte string new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding import json d = json.dumps(my_str) ... Read More

Assign Multiple Values to a Variable in Python

Ankith Reddy
Updated on 05-Mar-2020 05:40:07

1K+ Views

In Python, if you try to do something likea = b = c = [0,3,5] a[0] = 10You'll end up with the same values ina, b, and c: [10, 3, 5]This is because all three variables here point to the same value. If you modify this value, you'll get the change reflected in all names, ie, a,b and c. To create a new object and assign it, you can use the copy module.  examplea = [0,3,5] import copy b = copy.deepcopy(a) a[0] = 5 print(a) print(b)OutputThis will give the output −[5,3,5] [0,3,5]

Assign Dictionary Value to a Variable in Python

Lakshmi Srinivas
Updated on 05-Mar-2020 05:36:33

15K+ Views

You can assign a dictionary value to a variable in Python using the access operator []. examplemy_dict = {    'foo': 42,    'bar': 12.5 } new_var = my_dict['foo'] print(new_var)OutputThis will give the output −42exampleThis syntax can also be used to reassign the value associated with this key. my_dict = {    'foo': 42,    'bar': 12.5 } my_dict['foo'] = "Hello" print(my_dict['foo'])OutputThis will give the output −Hello

Combine Multiple Print Statements Per Line in Python

karthikeya Boyini
Updated on 05-Mar-2020 05:08:00

5K+ Views

You can combine multiple print statements per line using, in Python 2 and use the end argument to print function in Python 3.examplePython2.x print "Hello", print " world" Python3.x print ("Hello", end='') print (" world")OutputThis will give the output −Hello worldAnother thing you could do is put all the things in an array and call ''.join(array). examplearr = ["Hello", "world"] print(' '.join(arr))OutputThis will give the output −Hello world

Python Coding Standards and Best Practices

Chandu yadav
Updated on 05-Mar-2020 05:03:45

665 Views

You can use the PEP8 guide as a holy grail. Almost all python world uses this guide to write clean understandable and standard python code. This is available as an extension as a linter for all modern text editors. You can check it out at  http://www.python.org/dev/peps/pep-0008/Properly Structure your folders. All projects need proper structuring. This helps organize code better. Python has an opinionated folder structure that you should use.README.rst LICENSE setup.py requirements.txt sample/__init__.py sample/core.py sample/helpers.py docs/conf.py docs/index.rst tests/test_basic.py tests/test_advanced.pyUse doctests. The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to ... Read More

Print Multiple Blank Lines in Python

Samual Sam
Updated on 05-Mar-2020 05:02:36

3K+ Views

We can print multiple blank lines in python by using the character the number of times we need a blank line. For example, If you need 5 blank lines, you can use −Python 2.x: print "" Python 3.x: print("")You can use features like repetition operator in python to make this easier. For example,Python 2.x: print "" * 5 Python 3.x: print("" * 5)All of these commands will print 5 blank lines on the STDOUT.

Change the Color of Focused Links with CSS

karthikeya Boyini
Updated on 05-Mar-2020 05:01:04

1K+ Views

Use the :focus class to change the color of focused links. Possible values could be any color name in any valid format.ExampleYou can try to run the following code to implement the color of the focused link −                    a:focus {             color: #0000FF          }                     This is demo link    

Advertisements