Creating dictionaries

As previously stated, you create dictionaries and access items through a key. The key can be of any immutable type, such as a string, number, or tuple; basically, anything that can't be changed. Each key's associated value can be any type of object, including other dictionaries. The basic use of dictionaries is displayed in the following screenshot:

Basic dictionary operations

Line 19 creates the dictionary. Note that the brackets for dictionaries are curly braces, the separator between a key word and its associated value is a colon, and that each key:value is separated by a comma. In this example, the first mapping is a string to a string, the second is a string to an integer, and the last is a list to an integer.

Line 20 shows how to see how many items are contained within a dictionary. This value is only the number of mappings, not the individual keys/values contained within the dictionary.

Line 21 returns the value associated with the key cow. If you want to add a new item, you have to use the format in line 23—the name of the dictionary, followed by the new key within square brackets, and then what that key is equal to. If you try to make a new dictionary entry by trying to directly map the value to its key through a colon character (line 22), you will get an error.

After the new entry is created in line 23, we can verify it is there by simply calling the dictionary (line 24). Values in dictionary entries are completely accessible; in the case of line 25, we can increment the integer value by directly adding 1 to the appropriate key.

Compare this to lines 21 and 23. In line 21, calling the key returned its associated value. In line 23, adding the = sign to a key made a new dictionary entry. Thus, line 25 acts like a combination of those two—it gets the value associated to a key, and then makes a new dictionary entry by performing an operation on the value. In this case, we are simply adding 1 to the value, and then reassigning it as the key's associated value. Line 26 returns the entire dictionary to show that the new value associated with the chicken key has been incremented from 3 to 4.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.134