Trying to create new variables by strings from a list
<p><p>
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.</p>

<p>Edit: As requested, here's what the format for the data and my current code:<p>
State|City<p>
Washington|Seattle<p>
California|Los Angeles<p>
Washington|Kirkland<p></p>

<pre><code>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:
        cur.append(aa);
    for ab in dparse2:
        cur2.append(ab);
    del cur2[0];
    del cur[0];
    for ba in range(len(cur)):
        cur[ba] = cur[ba].split(",");
    sortloc(cur);
    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:
            state.append(dp[a][0]);
        city.append(dp[a][1]);
        s2.append(dp[a][0]);
    for ba in range(len(city)):
        for bb in range(len(state)):
            if s2[ba] == state[bb]:
                print("Matched stuff!");



start(PVC, KBP);
</code></pre>

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

<p>Thank you in advance for the help!</p>

<p>It is possible by using <code>eval()</code>, but you should <strong>REALLY</strong> 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:</p>

<pre class="lang-python prettyprint-override">
txt = '''state1, city1
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']
#}</pre>

python list csv variables