Dictionary is also a kind of data structure. It is a kind of method similar to list to store data. But getting the data is not a numerical index like list, but anything you want to use. In this way, you can use the dictionary as a database to store and organize data.
We can compare the functions of dictionaries and lists.
We can and can only find the elements in the list through numerical value!!!!!
What the dictionary does is it allows you to find elements from anything (not just numbers), it can associate one thing with another, no matter what its type.
In addition to numeric values, you can get stuff from the dictionary through strings, and you can add elements to the dictionary with strings, and there are more than just strings:
In addition to adding things to the dictionary that are not interesting, you can also delete:
Dictionary example
I won't take a screenshot. The code is for you to copy and paste.
The key principle of dictionary is mapping (or association)
states={ 'Orange': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } cities={ 'CA':'SAN Fracisco', 'MI':'Detroit', 'FL':'Jacksonvile' } cities['NY']='New York' cities['OR']='Portland' print('-' *10) print("NY State has: ", cities['NY']) print("OR State has: ", cities['OR']) print('-' *10) print("Michigan's abbreviation is: ", states['Michigan']) print("Florida's abbreviation is: ", states['Florida']) print('-'*10) print("Michigan has: ", cities[states['Michigan']]) print("Florida has: ", cities[states['Florida']]) print('-' *10) for state, abbrev in list(states.items()): print(f"{state} is abbreviated {abbrev}") print('-' *10) for abbrev, city in list(cities.items()): print(f"{abbrev} has the city {city}") print('-' *10) for state, abbrev in list(states.items()): print(f"{state} state is abbreviated {abbrev}") print(f"and has city {cities[abbrev]}") print('-' *10) state = states.get('Texas') if not state: print("Sorry, no Texas.") city = cities.get('TX', 'Does Not Exist') print(f"The city for the state 'TX' is: {city}")
- The difference between a dictionary and a list: a list is ordered, while a dictionary is a data structure that maps some items to others.
- Dictionary usage: all kinds of occasions where you need to view another value through one value.
- Use scope of list: for data that needs to be arranged in order