Created
September 9, 2016 23:03
-
-
Save mesbahamin/7c7e15e1d9e247e5cc87fe197fb2db1e to your computer and use it in GitHub Desktop.
An example of using nested python dictionaries to store log entries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pprint import pprint | |
# Create an empty dictionary: | |
log_entry = {} | |
# Add a key called 'ipaddr' to the dict, and assign | |
# a value to it: | |
log_entry['ipaddr'] = '192.168.1.1' | |
# Add more keys and corresponding values: | |
log_entry['port'] = 1234 | |
log_entry['pubkey'] = 'as;dfk3534562-a;sdkf' | |
log_entry['timestamp'] = '2016-09-09 15:41:37' | |
print('\nNow we can see what our dictionary looks like:') | |
pprint(log_entry) | |
print('\nOr just list the keys:') | |
print(log_entry.keys()) | |
print('\nOr just the values:') | |
print(log_entry.values()) | |
print('\nOr key, value tuples:') | |
print(log_entry.items()) | |
# You can nest dictionaries within each other. Let's make | |
# another dictionary to hold all the log entries: | |
log = {} | |
# We need to choose a key value for each entry. It could be | |
# anything. Let's make it the ip address. | |
key = log_entry['ipaddr'] | |
# Now we can add our previous dict, 'log_entry' as a value: | |
log[key] = log_entry | |
print('\nNow our log contains one entry:') | |
pprint(log) | |
# Let's make another entry, then add it to log: | |
another_entry = { | |
'ipaddr': '231.342.5.6', | |
'port': 4235, | |
'pubkey': 'a;sdlkpoiuaek;afa;', | |
'timestamp': '2016-09-09 15:55:13' | |
} | |
key = another_entry['ipaddr'] | |
log[key] = another_entry | |
print('\nNow our log contains two entries:') | |
pprint(log) | |
# Finally, if we add a key and value to log, | |
# and the key already exists, the previous value | |
# will be replaced: | |
entry_with_updated_timestamp = { | |
'ipaddr': '231.342.5.6', | |
'port': 4235, | |
'pubkey': 'a;sdlkpoiuaek;afa;', | |
'timestamp': '2017-08-03 12:27:17' | |
} | |
key = entry_with_updated_timestamp['ipaddr'] | |
log[key] = entry_with_updated_timestamp | |
print('\nOur log still contains two entries, but one of them has a different timestamp:') | |
pprint(log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment