- Learning Python for Forensics
- Preston Miller Chapin Bryce
- 401字
- 2021-08-20 10:17:02
Dictionaries
Dictionaries, otherwise known as dict, are another common Python data container. Unlike lists, this object does not add data in a linear fashion. Instead, data is stored as key and value pairs, where you can create and name unique keys to act as an index for stored values. It is important to note that, in Python 2, dictionaries do not preserve the order in which items are added to it. This is no longer true as of Python 3.6.5, though in general, we should not rely on the dict() object maintaining order for us. These objects are used heavily in forensic scripting, as they allow us to store data by name in a single object; otherwise, we may be left assigning a lot of new variables. By storing data in dictionaries, it is possible to have one variable contain very structured data.
We can define a dictionary by using curly braces ({}), where each key and value pair is delimited by a colon. Additionally, we can use the dict() class constructor to instantiate dictionary objects. Calling a value from a dictionary is accomplished by specifying the key in brackets following the dictionary object. If we supply a key that does not exist, we will receive a KeyError (notice that we have assigned our dictionary to a variable, a). While we have not introduced variables at this point, it is necessary to highlight some of the functions that are specific to dictionaries:
>>> type({'Key Lime Pie': 1, 'Blueberry Pie': 2})
<class 'dict'>
>>> dict((['key_1', 'value_1'],['key_2', 'value_2']))
{'key_1': 'value_1', 'key_2': 'value_2'}
>>> a = {'key1': 123, 'key2': 456}
>>> a['key1']
123
We can add or modify the value of a preexisting key in a dictionary by specifying a key and setting it equal to another object. We can remove objects using the pop() function, similar to the list pop() function, to remove an item in a dictionary by specifying its key instead of an index:
>>> a['key3'] = 789
>>> a
{'key1': 123, 'key2': 456, 'key3': 789}
>>> a.pop('key1')
123
>>> a
{'key2': 456, 'key3': 789}
The keys() and values() functions return a list of keys and values in the dictionary. We can use the items() function to return a list of tuples containing each key and value pair. These three functions are often used for conditionals and loops:
>>> a.keys()
dict_keys(['key2', 'key3'])
>>> a.values()
dict_values([456, 789])
>>> a.items()
dict_items([('key3', 789), ('key2', 456)])
- Extending Symfony2 Web Application Framework
- 白話網絡安全2:網安戰略篇
- Metasploit Penetration Testing Cookbook(Third Edition)
- 工業互聯網安全防護與展望
- Rootkit和Bootkit:現代惡意軟件逆向分析和下一代威脅
- 數字化轉型浪潮下的數據安全最佳實踐指南
- 硬黑客:智能硬件生死之戰
- 持續集成:軟件質量改進和風險降低之道
- 數字政府網絡安全合規性建設指南:密碼應用與數據安全
- 計算機網絡安全實驗指導
- 信息內容安全管理及應用
- 黑客攻防從入門到精通:命令版
- Web安全攻防從入門到精通
- 黑客攻防與電腦安全從新手到高手(超值版)
- 信息組織