Davis Davis - 13 days ago 5x
Python Question

Trying to create new variables by strings from a list

I've been scouring the ends of the internet for this, and I am well aware of how discouraged what I am trying to do is. I just can't figure out another way to achieve what I want.
Now, for my actual issue, I have been given a csv containing information of police shootings. The file contains the state of the case, with the city next to it. I want to a variable from each state's name recorded in the csv, and turn them into lists with the contents being the cities in that state. I've read some stuff about globals, but I'm just stumped about where to go from there. The language I'm using is python.

Edit: As requested, here's what the format for the data and my current code:
California|Los Angeles

PVC = open("PoliceViolence_city.csv", "r", errors="ignore");
KBP = open("KilledByPolice.csv", "r", errors="ignore");

def start(dparse, dparse2):
cur = [];
cur2 = [];
for aa in dparse:
for ab in dparse2:
del cur2[0];
del cur[0];
for ba in range(len(cur)):
cur[ba] = cur[ba].split(",");
for bb in range(len(cur2)):
cur2[bb] = cur2[bb].split(",");

def sortloc(dp):
merge = [];
state = [];
city = [];
s2 = [];
for a in range(len(dp)):
if dp[a][0] not in state:
for ba in range(len(city)):
for bb in range(len(state)):
if s2[ba] == state[bb]:
print("Matched stuff!");

start(PVC, KBP);

Ideally, my output will be something like: Washington = ["Seattle", "Kirkland"].

Thank you in advance for the help!


It is possible by using eval(), but you should REALLY not do that... a much more structured and safe way to accomplish your task would be to take the state name and make that a key in a dictionary:

txt = '''state1, city1, data1
state2, city2
state2, city3
state3, city4
state3, city4'''

states = {}
for line in txt.split('\n'):
    state, city = line.split(', ')
    if state not in states:
        states[state] = [] #create an empty list to hold all cities in a state
    if city not in states[state]: #don't put the same city in twice
        states[state].append(city) #insert the city into the list

#resulting structure:
#states = {
#    'state1': ['city1'],
#    'state2': ['city2', 'city3'],
#    'state3': ['city4']