- ArcPy and ArcGIS(Second Edition)
- Silas Toms Dara O'Beirne
- 259字
- 2025-04-04 19:02:02
Dictionaries
Dictionaries are denoted by curly brackets "{ }", and are used to create "key-value" pairs. This allows us to map values from a key to a value so that the value can replace the key, and data from the value can be used in processing. Here is a simple example:
>>> new_dic = {}
>>> new_dic['key'] = 'value'
>>> new_dic
{'key': 'value'}
>>> adic = {'key':'value'}
>>> adic['key']
'value'
Note that instead of referring to an index position, like lists or tuples, the values are referenced using a key. Also, keys can be any data object except lists (because they are mutable).
This can be very valuable when reading data from a shapefile or feature class for use in analysis. For example, when using an address_field as a key, the value would be a list of row attributes associated with that address. Look at the following example:
>>> business_info = { 'address_field' : ['100', 'Main', 'St'], 'phone':'1800MIXALOT' }
>>> business_info['address_field']
['100', 'Main', 'St']
Dictionaries are very valuable for reading in feature classes, and for easily parsing through the data by calling only the rows of interest, among other operations. They are great for ordering and reordering data for later use in a script.
Dictionaries are also useful for counting data items such as the number of times a value appears within a dataset, as seen in this example:
>>> list_values = [1,4,6,7,'foo',3,2,7,4,2,'foo']
>>> count_dictionary = {}
>>> for value in list_values:
if value not in count_dictionary:
count_dictionary[value] = 1
else:
count_dictionary[value] += 1
>>> count_dictionary['foo']
2