Created
June 15, 2017 21:40
-
-
Save vijayanandrp/f9f66ad9254b4096f826799157780238 to your computer and use it in GitHub Desktop.
How to do I understand List and Dict Python concepts in just 5 mins!!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
def lists_examples(): | |
print 'List examples in Python\n', '======================================' | |
L = [] | |
L = ['abc', 123, 1.23, {}] | |
L = ['Bob', 40.0, ['dev', 'mgr']] | |
L = list('spam') | |
L = list(range(-4, 4)) | |
print L | |
L = [x for x in 'vijay' if x in list('aeiou')] | |
print L | |
print 'x' in L | |
L.append(4) | |
print L | |
L.pop(1) # position based 'value' removing | |
print L | |
L.append('a') | |
L.extend(['v', 'j', 'y']) | |
L.remove(4) # search based 'value' removing | |
print L | |
import random | |
random.shuffle(L) | |
print L | |
random.shuffle(L) | |
print ''.join(L) | |
random.shuffle(L) | |
print ''.join(L) | |
random.shuffle(L) | |
L.sort() | |
print ''.join(L), L | |
del L[0] | |
print L | |
L = list(map(ord, 'abcdefghijklmnopqrstuvwxyz')) | |
print L, '\n' | |
def dict_examples(): | |
print 'Dictinary Examples (Mini Database)\n', '======================================' | |
# Different method for creating the dictionary values | |
D = {} | |
D = dict(name='vijay', age=24) | |
D = dict([('name', 'vijay'), ('age', 40)]) | |
D = {char: ord(char) for char in 'abcdefghijklmnopqrstuvwxyz'} | |
print D, '\n' | |
D = {'name': 'Vijay', 'age': 40, 'job': 'Engineer'} | |
print "dict = ", D | |
print "Dict keys to list ", list(D.keys()) # List Conversion | |
print "Dict to list ", list(D.items()) | |
D2 = {'company': 'None', 'location': 'IN'} | |
D.update(D2) # Merge Keys | |
D['new_field'] = 'Searching' # Adding or updating the values | |
print D | |
del D['new_field'] | |
print D.get('name') # Fetching | |
print D.pop('name') # Removing | |
print "keys = ", D.keys() | |
print "values = ", D.values() | |
print "items = ", D.items() | |
dict_using_zip = dict(zip(['name', 'new_field', 'age', 'job', 'location', 'company'], ['Vijay', 'Searching', 40, 'Engineer', 'IN', 'None'])) | |
print 'New = ', dict_using_zip, '\n' | |
dict_using_zip.clear() # Clearing all values | |
print dict_using_zip | |
def main(): | |
lists_examples() | |
dict_examples() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment