====== Python Data Structures ====== ===== Summary ==== [ ] = [[python:python-data-struct#list|List]] \\ { } = [[python:python-data-struct#dictionary|Dictionary]] \\ ( ) = [[python:python-data-struct#tuple|Tuple]] \\ Boolean:- [[python:python-data-struct#boolean_true_of_false]] \\ ===== List ===== Identified by square brackets and uses comma as seperator between elements. A list element is looked up by it's position in the list. list = ['value1', 'value2'] Remember, list indices start at ''0''!! To get the first item, start with the index 0:- firstitem = list[0] Add a new item to the end of the list with:- list.append(value3) Add a new item in the middle:- list.insert(value2) Select the last item in a list, this example splits a file url on directory separator (''/''), and selects the last item which should be the filename. Won't work on windows, but who cares!! fileName = key.split('/')[-1] Iterate over a list # for loop for index in list: print(index) ===== Dictionary ===== Identified by curly brackets and uses ":" to seperate out a Key and a Value. A value in a dictionary is referenced by it's key, the actual order of items stored in a dictionary can change, so you cannot retreive a value based on the position if you just print out the whole dictionary, you **have** to use the key. dict = { "key1": "value1", "key2": "value2" } If you want to look up the meaning of a word in English, you use a Dictionary to find the word (Key) and then read out the meaning of the word (Value). wordlist = { 'obfuscate': 'to make something less clear and harder to understand, especially intentionally', 'clarify': 'to make something clear or easier to understand by giving more details' } So:- definition = wordlist['obfuscate'] returns '' to make something less clear and harder to understand, especially intentionally '' As a dictionary is referenced by it's key to get a value, adding a new element is as easy as just creating a new key:value pair, there is no concept of insert as with a list. wordlist.update({'understand':'to know the meaning of something that someone says'}) wordlist['difficult'] = 'needing skill or effort' Testing if a key exists in a dictionary, ''key in dictionary'' evaluates to true or false:- if record["Key1"] in record: record["Key2"] = record["Key1"] Print just keys:- print(dictionary.keys()) Print all keys and values in a dictionary:- for key in dict: print(key, dict[key]) Print out each key/value line by line:- for key, value in get_metadata_response.items(): print(key, ' : ', value) Testing keys, check if a dictionary contains a specified key:- if 'user_a' in metadata.keys(): print("user_a supplied") elif 'user_b' in metadata.keys(): print("user_b supplied") else: print('Neither user A or B') ===== Tuple ===== A tuples is an immutable sequence. This means you cannot change it after it is created. tuple = (a, b, c) ===== Strings ===== In Python a string is a [[python:python-data-struct#list|list]] so you can address individual elements in it using list notation. So to select a portion of a string you can address each character as a list element:- account = '445156287145' removechar = 8 result1 = account[removechar:] result2 = account[removechar:len(account)] print(result1, result2) 7145 7145 ===== List of dictionaries ===== listOfDict = [ {'foo':1,'bar':123}, {'boo':3,'mar':234}, {'moo':5,'par':345} ] ===== Boolean True of False ===== Booleans are either "True or False" # Add user to user_model table, sql code to add new row OR update existing one:- # https://stackoverflow.com/questions/15383852/sql-if-exists-update-else-insert-into user_model_sql = f''' insert into user_model(highside_user_id, login_status) values ('{hsusername}', true) on duplicate key update highside_user_id = values(highside_user_id), login_status = values(login_status); ''' mysql_query = f"SELECT IF(login_status, 'true', 'false') from user_model WHERE highside_user_id = '{sessionname}'; "