Estimated reading time: 2 minutes
So you have a Python dictionary, and you want to retrieve data from it and print it to a screen. There are some characteristics of Python that first of all should be understood:
- They are mutable
- They also have the ability to grow and shrink as required.
- Data is accessed within the dictionary via keys.
The last point is very important as dictionaries do not have an index value, and this is why you get the TypeError you are here to solve for.
So let us recreate the problem
In the below code we have a dictionary called “userdata”, with its key-value pairs.
The loop is trying to retrieve the index value 1 for all the values in dai_data.
As can be seen, dai_data is trying to retrieve the last three index values within the dictionary.
As noted above the only way to access dictionary values is through their key values.
userdata = {
"name": "Data Analytics Ireland",
"Country": "Ireland",
"City": "Dublin",
"Age": "1000 years!",
}
dai_data = userdata[:3]
for i in dai_data:
print(i[1])
Output:
Traceback (most recent call last):
File "", line 8, in <module>
dai_data = userdata[:3]
TypeError: unhashable type: 'slice'
So how do we fix this problem?
First of all, values are accessed through the key within the dictionary
In the below dictionary the key values are: Name, Country, City, Age
userdata = {
"Name": "Data Analytics Ireland",
"Country": "Ireland",
"City": "Dublin",
"Age": "1000 years!",
}
print(userdata["Name"])
print(userdata["Country"])
print(userdata["City"])
print(userdata["Age"])
Output:
Data Analytics Ireland
Ireland
Dublin
1000 years!
As a result, now we are able to access the values associated with each key.
Did you know you could add a list to one of your key-value pairs?
In the above example, we focused on a single value, but we could also make a key equal to a list.
userdata = {
"Name": ["Joe","Jim"],
"Country": "Ireland",
"City": ["Dublin","Cork","Limerick"],
"Age": "1000 years!"
}
print(userdata["Name"])
print(userdata["Country"])
print(userdata["City"])
print(userdata["Age"])
Output:
['Joe', 'Jim']
Ireland
['Dublin', 'Cork', 'Limerick']
1000 years!