Python 07-Collections and Dictionaries

Posted by Desertwar on Tue, 25 Jan 2022 23:25:59 +0100

Python 07-Collections and Dictionaries

1. Collection - class set

1.1. Introduction

Python also contains collection types. A set is an unordered set of nonrepeating elements.

Its basic usage includes member detection and elimination of duplicate elements. Set objects also support mathematical operations such as union, intersection, difference, symmetric difference, and so on.

class set(object) - inherits object

  • Constructor
    set() -> new empty set object
    set(iterable) -> new set object
  • Lists can be built in many ways
    • Curly brackets {} or set() functions can be used to create collections.
    • To create an empty collection, you can only use set() instead of {} because the latter creates an empty dictionary
  • Sets also support derivative forms

1.2. Example usage

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words

>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

2. Dictionary - class dict

2.1. Introduction

Another useful Python built-in data type is the dictionary (see Mapping Type - dict).

Dictionaries are indexed by keywords, which can be of any immutable type, usually strings or numbers.

The best way to understand a dictionary is to think of it as a key: a set of value pairs where the key must be unique (in a dictionary).

A pair of braces creates an empty dictionary: {}.

Another way to initialize a dictionary is to place comma-separated key-value pairs within a pair of curly braces, which is how the dictionary outputs.

  • Constructor
class dict(object)
# New empty dictionary
   dict() 
  
#New empty dictionary initialized from pairs of mapped objects (keys, values)
   dict(mapping)
  
# Create a new dictionary with iterative objects
   dict(iterable)

# Initialize the new dictionary using name=value pairs in the keyword parameter list. For example: dict (one=1, two=2)
   dict(**kwargs)
  • Dictionaries can be created in several ways:

    • Use braces to separate keys by commas: Value pairs: {'jack': 4098,'sjoerd': 4127} or {4098:'jack', 4127:'sjoerd'}

    • Using a dictionary derivation: {}, {x: x ** 2 for x in range(10)}

    • Use type constructors: dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)

  • Example

    >>> a = dict(one=1, two=2, three=3)
    >>> b = {'one': 1, 'two': 2, 'three': 3}
    >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
    >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
    >>> e = dict({'three': 3, 'one': 1, 'two': 2})
    >>> a == b == c == d == e
    True
    

2.2. Main Methods

  • list(d)
    Returns a list of all keys used in dictionary d.

  • len(d)
    Returns the number of items in dictionary d.

  • d[key]
    Returns the key-based item in d. KeyError is raised if no key exists in the map.

  • d[key] = value
    Set d[key] to value.

  • del d[key]
    Remove d[key] from D. KeyError is raised if no key exists in the map.

  • key in d
    Returns True if a key exists in d, False otherwise.

  • key not in d
    Equivalent to not key in d.

  • iter(d)
    Returns an iterator whose elements are dictionary keys. This is a shortcut to iter(d.keys()).

  • clear()
    Remove all elements from the dictionary.

  • copy()
    Returns a shallow copy of the original dictionary.

  • get(key[, default])
    Returns the value of the key if it exists in the dictionary, otherwise returns default.

  • pop(key[, default])
    Remove the key if it exists in the dictionary and return its value, otherwise return default.

  • popitem()
    Remove from the dictionary and return a (key, value) pair. Key-value pairs are returned in LIFO order.

  • reversed(d)
    Returns an iterator that retrieves dictionary keys in reverse order. This is a shortcut to reversed(d.keys()).

  • setdefault(key[, default])
    If a dictionary has a key, return its value. If it does not exist, insert the key with a value of default and return default. Default defaults to None.

  • update([other])
    Update the dictionary with a key/value pair from an other, overwriting the original key. Returns None.

    update() accepts another dictionary object or an iterative object containing key/value pairs represented by tuples of two lengths or other iterative objects. If a keyword parameter is given, the dictionary is update d with its specified key/value pair: d.update(red=1, blue=2).

This group is the concept of the View Object Document

  • items()
    Returns a new view of dictionary items (key, value) pairs. See the View Object Document.
  • keys()
    Returns a new view made up of dictionary keys. See the View Object Document.
  • values()
    Returns a new view of dictionary values. See the View Object Document.
m = {1: "hello", 2: "world"}
print(m)
print(m.keys())
print(m.values())
print(m.items())
"""
{1: 'hello', 2: 'world'}
dict_keys([1, 2])
dict_values(['hello', 'world'])
dict_items([(1, 'hello'), (2, 'world')])
"""

Topics: Python