开发者

Python Inserting values into dictionary using a loop

I have a verses dictionary that contains these values:

{cluster1: 0, cluster2: 0, cluster3: 0}

i have a data file that has been read in and each line in the file has been represented as a string in a dictionary like this.

 [ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3"," 0,1,0,0,1,0,0,0,0,1,1,No,cluster2" ]

I want to be able to, for each line in the data file (represented as a string in a list), go through the dictionary and compare the Key values eg. cluster1 to see if it contains the substring "cluster1" 2 or 3. and then update the value in the dictionary accordingly. So the aim of the programme is to count the occurences of each cluster and have this represented as a dictionary with the clusternumber and the corresponding counts for each cluster.

I`m just not sure on the syntax to do this. here is my loop so far:

for verse in verses:
    for clusters[Key] in clusters:
        if clusters[Key] in verse:
            clusters.add(Key, +1) # tries to increment the value of 
                                  # the key if the key is in the string verse.
        else:
      开发者_运维百科      print "not in"

Could someone give me some advice on where to go?

Thanks


You're quite close. You need to look through keys of the dictionary:

for verse in verses:
  for k in cluster:
    if k in verse:
      clusters[k] += 1
    else: print "not in"


Use defaultdict and rsplit (split from right)

verses = [ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3"," 0,1,0,0,1,0,0,0,0,1,1,No,cluster2" ]

from collections import defaultdict

clusters = defaultdict(int)

for verse in verses:
    key = verse.rsplit(',',1)[1]
    clusters[key] += 1

print clusters

Output:

defaultdict(<type 'int'>, {'cluster2': 1, 'cluster3': 1})


l=[ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3"," 0,1,0,0,1,0,0,0,0,1,1,No,cluster2" ]
d={'cluster1': 0, 'cluster2': 0, 'cluster3': 0}
for line in l:
    tokens = line.split(',')
    d[tokens[-1]]+=1

print d

Returns

{'cluster2': 1, 'cluster3': 1, 'cluster1': 0}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜