User Tools

Site Tools


python:tuplelistdict

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python:tuplelistdict [2013/03/16 17:41] (current)
Line 1: Line 1:
 +==== PYTHON DATA TYPES: LISTS, TUPLES, DICTIONARIES ====
 +last update: 09.06.2011
 +
 +
 +**What are they?**
 +
 +**List:** simply an ordered collection of objects. Object can have any legal Python name and a list can grow dynamically. Lists are ordered sequence type. A index can be used for accessing elements.
 +
 +**Tuple:** is similar to a list, but it's a read-only version. The items cannot be added or removed from a tuple.
 +
 +**Dictionary**:​ unordered collection of objects pairs (key => value)
 +
 +
 +=== LIST ===
 +
 +Defining a list is just an assignment to a variable using = operator. The list is enclosed in square brackets.
 +
 +<code python>
 +list_numerical = [12, 35, 64, 4]
 +list_string = ["​Joe",​ "​Mary",​ "​Zoro"​]
 +list_sublist = ["​Python",​ "​PHP",​ ["​Another list", 2344]]
 +</​code>​
 +
 +The items in a list can accessed by an zero-based index, means that first element is list[0], the next list[1] and so on. If you want to access the last element, you can use negative index, list[-1]. For the previous item, list[-2] and so on.
 +
 +__Slice:__ a subset of a list. You can obtain a slice by referencing a list using a starting index and a ending index, separated by a colon (:).
 +
 +
 +<code python>
 +days_list = ["​Maandag",​ "​Dinsdag",​ "​Woensdag",​ \
 + "​Donderdag",​ "​Vrijdag",​ "​Zaterdag",​ "​Zondag"​]
 +items_count = len(days_list)
 +slice = days_list[ : 4] -> returns ['​Maandag',​ '​Dinsdag',​ '​Woensdag',​ '​Donderdag'​]
 +slice = days_list[-5 : -2] -> returns ['​Woensdag',​ '​Donderdag',​ '​Vrijdag'​]
 +</​code>​
 +
 +__Adding/​Removing elements__
 +
 +Add:
 +<code python>
 + listname.append("​elem"​) -> adds to the end of the list
 + listname.insert(2,​ "​Element"​) -> adds "​Element"​ at index 2
 + listname.extend(anotherlist) -> accepts only a list; add multiple elem
 + at the same time
 + list1 += list2 -> similar to extend
 +</​code>​
 +
 +Remove:
 +<code python>
 + listname.pop(index) -> remove an item by its index and then returns it
 + listname.remove(item) -> search the list and remove the first occurrence.
 +</​code>​
 +
 +
 +__Sorting a list__
 +
 +<code python>
 +weekdays_list.sort()
 +</​code>​
 +
 +Sorts the list based on the total value of each object. It modifies the order of the objects in the list itself.
 +
 +Sort() method can accept a comparison function as an argument. This function can accept two arguments and must return -1, 0, 1 depending on whether the first arg is smaller, equal or greater than the second one.
 +
 +<code python>
 +weekdays_list.sort(lambda x, y: some_function(x,​ y))
 +</​code>​
 +
 +Sort() method can also accept a key function. This key function should accept one argument that will be used to extract a key from each object from the list. The list will be then ordered by this extracted key.
 +
 +<code python>
 +weekdays_list.sort(key=str.lower)
 +weekdays_list.reverse()=weekdays_list.sort(reverse=1) -> sorting in reverse order
 + reverse() - just reverses the string w/out any alteration
 +</​code>​
 +
 +
 +=== TUPLES ===
 +
 +
 +They cannot be modified after initial declaration. They use parentheses.
 +
 +<code python>
 +tuple_vegetables = ('​melon',​ '​carrot',​ '​potato'​)
 +</​code>​
 +
 +**the data is immutable (static)** \\ 
 +**faster access than a list**
 +
 +
 +**NOTE:** the tuple constructor is the //comma//, not the parentheses! (but we use them for clarity). For example:
 +
 +<code python>
 +a = 1,2
 +
 +type(a)
 +<type '​tuple'>​
 +</​code>​
 +
 +
 +
 +Transforming tuple -> list using function list(). Reverse: tuple().
 +
 +<code python>
 +list_numbers = [2, 5, 4, 6]
 +tuple_numbers = tuple(list_numbers)
 +list_again = list(tuple_numbers)
 +</​code>​
 +
 +
 +=== DICTIONARIES ===
 +
 +
 +Assign a value or a group of values to a key. The keys must be integers, string or immutable tuple (made up of strings or/and integers).
 +
 +
 +__Defining dictionaries:​__
 +
 +<code python>
 +some_dict = { '​one'​ : 1, '​two'​ : 2, '​three'​ }
 +another_dict = dict(
 +    one = 1, two = 2,
 +    three = 3
 +)
 +</​code>​
 +
 +
 +//Note: the dict() method accepts only strings that are valid identifiers (variable names) to be mapped. So, a dict(1 = one) will **not work**.//
 +
 +__Dictionaries types:__
 +
 +   ​- ​ one to one - key to value association
 +
 +<code python>
 +dict_numbers = { 1 : '​one',​ 2 : '​two',​ 3 : '​three'​ }
 +</​code>​
 +
 +   - one to many - can be accomplished using list objects as values
 +
 +<code python>
 +dict_numbers = { 1 : ['​one',​ '​two',​ '​three'​],​ 2 : ['​four',​ '​five'​] }
 +</​code>​
 +
 +   - many to many - can be accomplished using tuples as keys, lists as values
 +
 + tuple_as_key_1 = (1, 2, 3, 4, 5)
 + tuple_as_key_2 = (4, 6, 7)
 + set_dict = {tuple_as_key_1 : ['​sd',​ '​ff'​],​ tuple_as_key_2 : ['​sd',​ '​fd'​]}
 +<code python>
 +=> {(1, 2, 3, 4, 5): ['​sd',​ '​ff'​],​ (4, 6, 7): ['​sd',​ '​fd'​]}
 +</​code>​
 +
 +
 +__Adding a value__
 += setup a key to correspond to a value - if already exists, replace the key value, otherwise just add the pair key,value to the dictionary Keys are case-sensitive (Key is not key).
 +
 +__Retrieving a value__
 +
 +<code python>
 +dict_example = { 1 : '​one',​ 2 : '​two',​ '​key'​ : 3}
 +dict_example.keys() => [1, 2, '​key'​]
 +dict_example.values() => ['​one',​ '​two',​ 3]
 +dict_example.items() => [(1, '​one'​),​ (2, '​two'​),​ ('​key',​ 3)]
 +dict_example[2] => two
 +dict_example.get(12,​ 43) # use this to prevent unexisting key to throw an error
 +</​code>​
 +
 +__Slicing a dictionary__
 +
 +No specific method: just retrieve all keys, make some slicing using the keys list, and then in a for cycle retrieve (get or pop) the values from the dictionary for sliced keys.
 +
 +__Swaping keys - values in a dictionary__
 +
 +<code python>
 +intial_dict = { 1 : '​one',​ 2 : '​two',​ '​key'​ : 3}
 +swapped_dict = {}
 +for key, val in intial_dict.iteritems():​
 + swapped_dict[val] = key
 +</​code>​
 +
 +__Sorting after keys/​values__
 +
 +<code python>
 +sorted(dict.keys()) # or simply sorted(dict)
 +sorted(dict.values())
 +</​code>​
 +
 +
 +__Iterate over a dictionary__
 +
 +<code python>
 +for key in dictionary.iterkeys():​
 +    print key, dictionary[key]
 +for key in dictionary.keys():​
 +    print key, dictionary[key]
 +for key, value in dictionary.items():​
 +    print key, value
 +</​code>​
 +
 +
 +__Looking for a value/key__
 +
 +<code python>
 +# look for a known value and return the key
 +return [ k for k,v in our_dictionary.items() if v == our_value ]
 +# look for a known key and return the value
 +return [ our_dictionary[known_key] if known_key in our_dictionary else "​Unknown key" ]
 +</​code>​
  
python/tuplelistdict.txt ยท Last modified: 2013/03/16 17:41 (external edit)