14

Python Day 4: Dictionaries

 4 years ago
source link: https://rowelldionicio.com/python-day-4-dictionaries/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python Day 4: Dictionaries

September 23, 2018 By Rowell Leave a Comment

Dictionaries

Indexes for dictionaries are called keys. Keys are associated with a value called a key-value pair. A dictionary is unordered. Compared to a List, there is no index starting at 0.

Dictionaries are typed with braces [python]{}[/python]. To assign a dictionary to the client1 variable:

[python]client1 = {'rssi': -52, 'channel': 36, 'noise': -96, 'tx rate': 600, 'mcs': 9}[/python]

The keys within this dictionary are rssi, channel, noise, tx rate, and mcs. The values for those keys are -52, 36, 96, 600, and 9, respectively.

To access a value through a key it is performed by:

[python]
client1[‘channel’]
36
[/python]

Trying to call a key that doesn’t exist in the dictionary will result in a KeyError error message.

[python]
client1['bssid']
Traceback (most recent call last):
File "", line 1, in 
KeyError: 'bssid'
[/python]

With methods, values can be returned from a dictionary. Let’s say I want to print out the key and value of client1. I’ll use a for-loop to iterate through each of the key-value pairs and print them out using the items() method.

[python]
for i in client1.items():
print(i)
('rssi', -52)
('channel', 36)
('noise', -96)
('tx rate', 600)
('mcs', 9)
[/python]

If we just needed to print out the keys we would use the keys() method. Again, I’ll use the for-loop to iterate through the keys and print them out:

[python]
for k in client1.keys():
print(k)
rssi
channel
noise
tx rate
mcs
[/python]

If we wanted just the values we can do the same for-loop but call the values() method:

[python]
for v in client1.values():
print(v)
-52
36
-96
600
9
[/python]

Filed Under: Coding Tagged With: dictionaries, python


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK