Programmer's Python Data - The Dictionary
Written by Mike James   
Monday, 18 September 2023
Article Index
Programmer's Python Data - The Dictionary
Hashing
Dictionary Versus List

Dictionary Versus List

There are some other important differences between lists and dictionaries. In particular, you can't use an element of a list unless it has already been created in one way or another, but for a dictionary it is permissible. That is, if age_list is a list then age_list[0] = 19 will result in a run-time error unless there is already an element 0. However, if age is a dictionary, age["Lucy"] = 19 never causes an error and will either create the new entry or update an existing one. Notice that if you try to access a dictionary entry that doesn’t have a key then you do generate an exception, see later.

To summarize the distinction between lists and dictionaries:

  • a list assignment updates existing elements

  • a dictionary assignment creates and or updates elements

  • accessing a list or a dictionary entry that doesn’t exist throws an exception.

To initialize a dictionary you use curly brackets to distinguish it from a list which uses square brackets. That is, age = {} is a dictionary while age = [] is a list.

Just as you can initialize a list by writing its elements within square brackets, for example:

age_list = [19,20,25,18]

you can initialize a dictionary using curly brackets:

age_dict = {"lucy":19,"harry":20,"ian":25,"sue":28}

Notice that the initialization is a tiny bit more complicated because you have to specify the key and the value. The way that you do this is to use the notation key:value, but apart from this the two usages are similar. Also notice that we do need quotes around each of the keys because in this case they are strings. Strings are so often the keys used in a dictionary that it can be difficult to remember that any hashable object can be a key.

Notice that while you use curly brackets to initialize a list you use square brackets for indexing, as with a list. What this means is that when you see x[42] = 0 you cannot tell if x is a list or a dictionary as dictionaries can have integer keys.

If you follow how the dictionary is implemented you will already know that (key,value) pairs are stored in the order in which they are added to the dictionary. This generally isn’t important, but it does control the order that you iterate through a dictionary, see later. If you change a value the position in the order doesn’t change. Only deleting an entry and adding it again changes the order.

In Chapter but not in this extract:

  • Dictionary Operations
  • Views
  • Key Loops
  • Sorting and Order
  • Combining and Copying Dictionaries
  • Complex Dictionaries
  • ChainMap

 Summary

  • The dictionary is like the list which you can use to store and retrieve values based on keys of a wide range of types.

  • Creating a list can be done by assigning an empty list {} or by using the constructor. You can also set initial values in the constructor or the curly brackets.

  • Dictionaries work using a hash function to store the value at a known location.

  • The alternative to a dictionary is to search a list, an operation that takes a time proportional to the number of items. A dictionary can return a value in a constant time, but it uses more storage than the list would.

  • Dictionaries and lists are very similar, but there are some important differences – you cannot store a value in a list location that doesn’t already exist, but you can create a new element in a dictionary by assignment.

  • You can use in and not in to test to see if a key is already in a dictionary and the get method to return a default value if the key doesn’t exist.

  • A view is a mapping into a dictionary rather than a copy of any part of it.

  • You can iterate through a dictionary by keys in a simple for loop.

  • To iterate through a dictionary by value or key value pairs you need a view.

  • Dictionaries can be sorted using the sort function but mostly the way keys are looked up means sorting is inappropriate.

  • You can delete, copy and combine dictionaries.

  • As the value stored in a dictionary can be any valid Python data type, you can create some very complex dictionaries that sort lists, tuples and even other dictionaries as their value.

  • The chainmap allows you to combine dictionaries for lookup.

Programmer's Python
Everything is Data

Is now available as a print book: Amazon

pythondata360Contents

  1. Python – A Lightning Tour
  2. The Basic Data Type – Numbers
       Extract: Bignum
  3. Truthy & Falsey
  4. Dates & Times
       Extract Naive Dates ***NEW!!!
  5. Sequences, Lists & Tuples
       Extract Sequences 
  6. Strings
       Extract Unicode Strings
  7. Regular Expressions
  8. The Dictionary
       Extract The Dictionary 
  9. Iterables, Sets & Generators
       Extract  Iterables 
  10. Comprehensions
       Extract  Comprehensions 
  11. Data Structures & Collections
       Extract Stacks, Queues and Deques
      
    Extract Named Tuples and Counters
  12. Bits & Bit Manipulation
       Extract Bits and BigNum 
  13. Bytes
       Extract Bytes And Strings
       Extract Byte Manipulation 
  14. Binary Files
  15. Text Files
  16. Creating Custom Data Classes
        Extract A Custom Data Class 
  17. Python and Native Code
        Extract   Native Code
    Appendix I Python in Visual Studio Code
    Appendix II C Programming Using Visual Studio Code

<ASIN:1871962765>

<ASIN:1871962749>

<ASIN:1871962595>

<ASIN:B0CK71TQ17>

<ASIN:187196265X>

Related Articles

Creating The Python UI With Tkinter

Creating The Python UI With Tkinter - The Canvas Widget

The Python Dictionary

Arrays in Python

Advanced Python Arrays - Introducing NumPy

espbook

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner



Last Updated ( Monday, 18 September 2023 )