DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

Tuples can, however, be used to assign a set of variables
quickly:


Click here to view code image


>>> (a, b, c) = (12, 'Fred',18)
>>> c
18

Dictionaries


A dictionary provides another way of creating a
collection of items. Why do you need another way of
storing data when you already have lists and tuples? A
list is an ordered set of items tracked by an index. What
if you need to access data that is tied to a certain value,
such as a person’s name? This capability is exactly why
you need dictionaries in Python. A dictionary saves a ton
of effort by giving you a built-in system for storing data
in a key:value pair. As when you use labels on files in a
filing cabinet, you can assign data to a key and retrieve it
by calling that key as if you are pulling a file from the
cabinet. Dictionaries don’t have any defined order; all
you need is the key—and not some index number—to get
access to your data. There are some rules regarding
dictionaries.


Keys: A dictionary’s keys are limited to only using immutable values
(int, float, bool, str, tuple, and so on). No, you can’t use a list as a key,
but you can use a tuple, which means you could use a tuple as a key
(immutable) but you can’t use a list as a key (mutable).
Values: A value can be any Python object or any combination of
objects.

To create a dictionary, you use braces and your key and
value separated by a colon. You separate multiple items
with commas. Here’s an example:


Click here to view code image


>>> cabinet = { "scores":(98,76,95),
"name":"Chris",
"company":"Cisco"}
Free download pdf