Home > Back-end >  Matplotlib.pyplot TypeError and Python KeyError
Matplotlib.pyplot TypeError and Python KeyError

Time:10-19

I am trying to create a menu program using a csv file, by asking the user for 5 ncic codes and saving that info as a json file.

There are a couple of things wrong here:

  1. export_data() is not working.

     Traceback (most recent call last): File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 254, in <module> main() File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 203, in main export_data(count_ncic_code_dict, count_district_dict, count_beat_dict) File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 139, in export_data if main_dict['count of crime by ncic code'] is None: KeyError: 'count of crime by ncic code'
    
  2. I am trying to make a bar graph (and save it as a png) of the 5 ncic codes from the user, however, I have a graph but it is blank.

     TypeError: bar() missing 1 required positional argument: 'height'
    
  3. I try to exit() in main() option 4, but it doesn't exit.

I have been looking at this over and over and I am stuck and at a lost and I am tired. If anyone has some ideas I would greatly appreciate it.

This is my whole code.

import matplotlib.pyplot as plt
import json
import csv


#create list
def create_list():
    '''Create  list from csv file'''
    data = []
    with open('crime.csv') as file:
        lines = csv.reader(file)
        next(lines)
        for line in lines:
            data.append(line)
                    
    return data
    

#list codes and added them to dic
def get_ncic_code_data(data):

    ncic_code_list = ['0-999', '1000-1999', '2000-2999', '3000-3999', '4000-4999', '5000-5999', '6000-6999', '7000-7999', '8000-8999']
    ncic_code_dict = dict.fromkeys(ncic_code_list)

    #loop with dic and ncic code
    for x in data:
        if int(x[6]) >=0 and int(x[6]) <= 999:
            if ncic_code_dict['0-999'] is None:
                ncic_code_dict['0-999'] = [x[5]]
            else:
                ncic_code_dict['0-999'].append(x[5])
        elif int(x[6]) >= 1000 and int(x[6]) <= 1999:
            if ncic_code_dict['1000-1999'] is None:
                ncic_code_dict['1000-1999'] =[x[5]]
            else:
                ncic_code_dict['1000-1999'].append([x[5]])
        elif int(x[6]) >= 2000 and int(x[6]) <= 2999:
            if ncic_code_dict['2000-2999'] is None:
                    ncic_code_dict['2000-2999'] = [x[5]]
            else:
                 ncic_code_dict['2000-2999'].append([x[5]])
        elif int(x[6]) >= 3000 and int(x[6]) <=3999:
            if ncic_code_dict['3000-3999'] is None:
                ncic_code_dict['3000-3999'] = [x[5]]
            else:
                ncic_code_dict['3000-3999'].append([x[5]])
        elif int(x[6]) >= 4000 and int(x[6]) <= 4999:
           if ncic_code_dict['4000-4999'] is None:
               ncic_code_dict['4000-4999'] = [x[5]]
           else:
               ncic_code_dict['4000-4999'].append([x[5]])
        elif int(x[6]) >= 5000 and int(x[6]) <= 5999:
            if ncic_code_dict['5000-5999'] is None:
              ncic_code_dict['5000-5999'] = [x[5]]
            else:
                ncic_code_dict['5000-5999'].append([x[5]])
        elif int(x[6]) >= 6000 and int(x[6]) <= 6999:
           if ncic_code_dict['6000-6999'] is None:
               ncic_code_dict['6000-6999'] = [x[5]]
           else:
               ncic_code_dict['6000-6999'].append([x[5]])
        elif int(x[6]) >= 7000 and int(x[6]) <= 7999:
          if ncic_code_dict['7000-7999'] is None:
              ncic_code_dict['7000-7999'] = [x[5]]
          else:
              ncic_code_dict['7000-7999'].append([x[5]])
        elif int(x[6]) >= 8000 and int(x[6]) <= 8999:
            if ncic_code_dict['8000-8999'] is None:
             ncic_code_dict['8000-8999'] = [x[5]]
        else:
             ncic_code_dict['8000-8999'].append([x[5]])
        return ncic_code_dict


#get codes and information

def get_district_data(data):
    district_dict = {}
    for x in data:
        if x[2] in district_dict:
            district_dict[x[2]].append(x[5])
        else:
            district_dict[x[2]] = [x[5]]
        return district_dict

def get_beat_data(data):
        beat_dict = {}
        for x in data:
            if x[3].strip() in beat_dict:
                beat_dict[x[3].strip()].append(x[5])
            else:
                beat_dict[x[3].strip()] = [x[5]]
        return beat_dict
    
    
def get_ncic_list(data):
    ncic_list = []
    for x in data:
        ncic_list.append(x[6])
    return ncic_list

def get_count(ncic_code_dict, district_dict, beat_dict):
    count_ncic_code_dict = {}
    for key in ncic_code_dict:
        if ncic_code_dict[key] is None:
            count_ncic_code_dict[key] = 0
        else:
            count_ncic_code_dict[key] = len(ncic_code_dict[key])
    
    count_district_dict = {}
    for key in district_dict:
        if district_dict[key] is None:
            count_district_dict[key] = 0
        else:
            count_district_dict[key] = len(district_dict[key])
        
        count_beat_dict = {}
        
        for key in beat_dict:
            if beat_dict[key] is None:
                count_beat_dict[key] = 0
            else:
                count_beat_dict[key] = len(beat_dict[key])
                
    return count_ncic_code_dict, count_district_dict, count_beat_dict


#create json file
def export_data(count_ncic_code_dict, count_district_dict, count_beat_dict):
    '''saves to json file'''
    main_list = ['count of crime by ncic code, count of crime by district, count of crime by beat']
        
    main_dict = dict.fromkeys(main_list)
        
    for i in range(len(count_ncic_code_dict)):
        for key, value in count_ncic_code_dict.items():
            if main_dict['count of crime by ncic code'] is None:
                    main_dict['count of crime by ncic code'] = {key: value}
            else:
                  main_dict['count of crime by ncic code'].update({key: value})
    for i in range(len(count_district_dict)):
        for key, value in count_district_dict.items():
            if main_dict['count of crime by district'] is None:
                    main_dict['count of crime by district'] = {key: value}
            else:
                    main_dict['count of crime by district'].update({key: value})
    for i in range(len(count_beat_dict)):
        for key, value in count_beat_dict.items():
            if main_dict['count of crime by beat'] is None:
                    main_dict['count of crime by beat'] = {key: value}
            else:
                    main_dict['Count of crime by beat'].update({key: value})
                    
                    
    with open("October.json", "w") as outfile:
            json.dump(main_dict, outfile)
            
    outfile.close()
    print("saved  information to json file")


#bar graph
def plot_graph(ncic_list_user, count_list, chart_title):

    fig, ax = plt.subplots(figsize=(5, 5))
    plt.get_current_fig_manager().set_window_title('Crime Bar Graph')
    ax.pie(count_list, autopct='%.1f%%')
    ax.set_title(chart_title)

    plt.legend( loc='right', labels=ncic_list_user)
    plt.tight_layout()

    fig.savefig('crime.png')

    plt.show()

#user display
def main():
    data = create_list()

    menu='''
    Menu:
        1. Display Crime Report list that includes NCIC code and by district and by beat:
        2. Display all crimes for a beat number.
        3. Count of 5 NCIC codes display them and show a bar chart.
        4. Quit
        '''
    print(menu)
    selection = input("Enter number from the menu:")

    if selection == '1':
        '''Display a crime report that will list:
        count of crimes by ncic code by 1000 (0-999, 1000-1999, etc) and by district and by beat'''
        ncic_code_dict = get_ncic_code_data(data)
        district_dict = get_district_data(data)
        beat_dict = get_beat_data(data)
        count_ncic_code_dict, count_district_dict, count_beat_dict = get_count(ncic_code_dict, district_dict, beat_dict)
        
        print()
        export_data(count_ncic_code_dict, count_district_dict, count_beat_dict)
        
    elif selection == '2':
        '''Ask the user for a beat number and show all the crimes for that beat'''
        print("Beat numbers:")
        beat_dict = get_beat_data(data)
        for key, value in beat_dict.items():
            print (key, end='')
        print()
        
        user_input = input("Enter beat number:")
        
        print("Crimes for beat {}: ".format(user_input))
        for key, value in beat_dict.items():
            if key == user_input:
                for val in value:
                    print(val)
                    
    elif selection == '3':
        '''Ask user for 5 ncic numbers and create a bar graph
        ask the user for a title of the chart and then display the chart'''
        ncic_code_dict = get_ncic_code_data(data)
        print("Ncic codes:")
        ncic_list = get_ncic_list(data)
        
        theset = set(ncic_list)
        
        for x in theset:
            print(x, end='')
            
        ncic_list_user = []
        
        print("Enter 5 NCIC codes:")
        
        for i in range(1, 5 1):
            user_input = input("Enter NCIC codes #{}: ".format(i))
            ncic_list_user.append(user_input)
            
        chart_title = input("Enter chart title:")
        
        
        count_list = []
        
        for x in ncic_list_user:
            count_list.append(ncic_list.count(x))
          
            plot_graph(ncic_list_user, count_list, chart_title)
        
            
    elif selection == '4':
        exit()
        
main()

CodePudding user response:

export_data error

To fix the error for export traceback

Traceback (most recent call last): File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 254, in <module> main() File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 203, in main export_data(count_ncic_code_dict, count_district_dict, count_beat_dict) File "C:\Users\dddst279\My Files\Google Drive\My Drive\Final Project - Deidra Dayak.py", line 139, in export_data if main_dict['count of crime by ncic code'] is None: KeyError: 'count of crime by ncic code'

you need to change if main_dict['count of crime by ncic code'] is None:, if main_dict['count of crime by district'] is None:, and if main_dict['count of crime by beat'] is None: to these:

if main_dict.get('count of crime by ncic code') is None:
if main_dict.get('count of crime by district') is None:
if main_dict.get('count of crime by beat') is None:

The error is occurring because you are trying to access a key that is not there, and won't return anything. The get() method is a safe way to access an element's keys if it is possible that it doesn't exist and will return None if it doesn't.

Bar Chart

For the bar chart, you need to add another variable when you call the function that will take care of the height that you would like the bar chart to be. (it would be recommended that you provide an error with that stack trace)

  • Related