Skip to content

Instantly share code, notes, and snippets.

@gdgupta11
Created June 7, 2020 19:14
Show Gist options
  • Save gdgupta11/e8410c9dd69b579749eebc17c7a4ec31 to your computer and use it in GitHub Desktop.
Save gdgupta11/e8410c9dd69b579749eebc17c7a4ec31 to your computer and use it in GitHub Desktop.

Python Small learning functions and examples

Reading and Writing JSON Objects and Files

Reading from python objects

"""
	When you want to read from python string object and conver to python Dict:
		json.loads(pythonString) --> result is python dict 
	when you want to write to 
"""
import json
string = '{"id":"09", "name": "Nitin", "department":"Finance"}' 
# This will convert json string into json dictionary in python
jdict = json.loads(jobject)
print(jdict)
{'id': '09', 'name': 'Nitin', 'department': 'Finance'}

# Converting a json dict into python string object

jstring = json.dumps(jdict)
print(jstring)

#ouput: 
"{'id': '09', 'name': 'Nitin', 'department': 'Finance'}"

Opening and reading JSON from file

"""
When you are reading from file:
	use json.load()
When you want to write to a file:
	use json.dump()
"""
import json
with open('data.json', r) as f:
    data = json.load(f)

print(data)
# Python Dictonary
{'fruit': 'Apple', 'size': 'Large', 'color': 'Red'}

# Use this dictionary to write back into file

with open('newfile.json', 'w') as f:
    json.dump(data, f)

# that should create a new file in cwd with name of newfile.json

Capitalise first character of each word in the string

#!/bin/python3

# string.capitalize for making the first letter in Upper case

a_string = input().split(' ')
result = ' '.join((word.capitalize() for word in a_string))
print(result)

Finding the Occurrences of a substring in a string

# this will give list of index on which the substring is appearing 
string = "hello"
indexList= [n for n in range(len(string)) if string.find('ll', n) == n]

Output:
[2, 3]

Getting Letter and index of that letter in a string and converting it into list

string = "BANANA"
# here i represents index of letter in the string and letter represents letter
list1 = [letter for i, letter in enumerate(string)]

# If you want to find occurences of a letter in this string then:

t = "A"
list2 = [letter for i, letter in enumerate(string) if letter == t]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment