Python's 'dict' is an efficient key/value hash table structure that uses key:value pairs within braces. Values can be looked up or set using square brackets, and keys can be strings, numbers, or tuples, while other types may not work correctly. The document also explains how to build a dict, check for keys, and iterate over its contents using various methods.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
5 views2 pages
Testpy
Python's 'dict' is an efficient key/value hash table structure that uses key:value pairs within braces. Values can be looked up or set using square brackets, and keys can be strings, numbers, or tuples, while other types may not work correctly. The document also explains how to build a dict, check for keys, and iterate over its contents using various methods.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2
Python Dict and File
bookmark_border
Dict Hash Table
Python's ef cient key/value hash table structure is called a "dict".
The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty dict" is just an empty pair of curly braces {}.
Looking up or setting a value in a dict uses square brackets, e.g.
dict['foo'] looks up the value under the key 'foo'. Strings, numbers, and tuples work as keys, and any type can be a value. Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable). Looking up a value which is not in the dict throws a KeyError -- use "in" to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case).
## Can build up a dict by starting with the empty dict {}
## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega'
fi print(dict['a']) ## Simple lookup, returns 'alpha' dict['a'] = 6 ## Put new key/value into dict 'a' in dict ## True ## print(dict['z']) ## Throws KeyError if 'z' in dict: print(dict['z']) ## Avoid KeyError print(dict.get('z')) ## None (instead of KeyError)
A for loop on a dictionary iterates over its keys by default. The
keys will appear in an arbitrary order. The methods dict.keys() and dict.values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most ef cient way to examine all the key value data in the dictionary. All of these lists can be passed to the sorted() function. fi