user2954166
user2954166

Reputation: 23

Appending part of a string to a dictionary

say I have a list, items: ['a01:01-24-2011:s1', 'a03:01-24-2011:s2', 'a02:01-24-2011:s2'] which is structured as [animalID:datevisited:stationvisited] for each entry, and wished to count the number of times a station is visited, how would I do so? There are only two s tations so if i split it into two count functions thats not a hassle I've tried

def counts_station:
   for item in items:
   counts={}
   if item[-2] in counts:
    counts[item[-2]]=counts[item[-2]]+1
   else:
    counts[item[-2]]=1
   returns counts

as well as

def counts_station:
   for item in items:
    station=item[-2]
    if station in counts:
         counts[station]=counts[station]+1
    else:
         counts[station] = 1
    returns counts

help!?

Upvotes: 1

Views: 67

Answers (1)

beroe
beroe

Reputation: 12316

You need to split your string into sub-items before trying to use it as a key, use the range [-2:] instead of just -2, or just take the last character of the string (1 or 2), not the second-to-last. You also had some small errors in your code: needing to initialize counts as an empty dictionary:

items = ['a01:01-24-2011:s1', 'a03:01-24-2011:s2', 'a02:01-24-2011:s2']

def counts_station(items):
    counts={}
    for item in items:
        station=item[-1]
        if station in counts:
            counts[station]=counts[station]+1
        else:
            counts[station] = 1
    return counts

Another way to do this use .get() with a default value of 0 that is returned if the key doesn't exist:

def counts_station(items):
    counts={}
    for item in items:
        station=item[-1]
        counts[station]=counts.get(station,0) + 1
    return counts

Upvotes: 1

Related Questions