I am using a nested list which contains various types of crimes. To clarify, crimeDescription
is formatted as such: [['Murder'], ['Assault'], ... , ['Stalking'], ['Rape']]
. I am looking to create a dictionary that will hold every value/crime that is in this list and record its frequency, or how often it appears in the data set. Since the keys inside dictionaries can't be lists, I am attempting to access the string inside of each nested list, by calling its index i[0] in the for loop. When I run the following program:
#TypesOfCrime --> a List containing all different types of crime that's happened in LA
TypesOfCrime = []
CrimeFreq = {}
for i in crimeDescription:
if i not in TypesOfCrime:
i = i[0]
CrimeFreq[i] = 1
elif i in TypesOfCrime:
i = i[0]
CrimeFreq[i] += 1
I get the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-75-a8698e79e96a> in <module>()
5 if i not in TypesOfCrime:
6 TypesOfCrime.append(i)
----> 7 CrimeFreq[i[0]] = 1
8 elif i in TypesOfCrime:
9 CrimeFreq[i[0]] += 1
TypeError: 'float' object is not subscriptable
What am I doing wrong? How can I create a dictionary containing each different value that is in my nested list? Any advice will be helpful.
To count something with a dict, check if the key already exists and then increment the value, otherwise add the key with value 1:
crime_freq = {}
for current_crime in crimeDescription:
crime = current_crime[0]
if crime in crime_freq:
crime_freq[crime] += 1
else:
crime_freq[crime] = 1
The modern way to solve your problem is to use a collections.Counter
and a generator expression:
crime_freq = collections.Counter(crime[0] for crime in crimeDescription)
Do you want to if key not existence, created value OR if key existence, add value.
I recommendation using setdefault() method.
crime_freq = {}
for current_crime in crimeDescription:
crime = current_crime[0]
crime_freq.setdefault(crime, 0)
crime_freq[crime] += 1
If using setdefault() method, code is simple.
I usually using setdefault() method frequently.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.