how to insert values into a list in python.. with a few extra conditions
hi i have a list of tuples like this:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
and i wish to append each individual tuple to a dictionary as the dictionarys key.
i want the format to look like this.
dict = {"wealth-gain": value, "gain-burnt": value ......}
how would i create a loop that will go through each tuple in the bigrams list and append it to the dictionary?
Heres what i have
For word in bigrams:
dict[(0+"-"+1) = dict
basicaly i want to take each tuple and add a "-" in between each word in the tuple then append that to a dictionary?
Any ideas how to do this?
Also if the bigram that is going to be appended to the dictionary matches a bigram that is already in the dictionary i would not like to add that bigram to the dictionary. Rather i woul开发者_StackOverflow中文版d like to increment the value of the bigram already in the dictionary. Any ideas how to do that?
Thanks.
You can use the join
method:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
dict_ = {}
for tup in bigrams:
k = '-'.join(tup)
dict_[k] = data.setdefault(k,0) + 1
or express the initialization with a generator:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
dict_ = dict(('-'.join(tup), 0) for tup in bigrams)
How about:
d = {}
val = 0
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
for word in bigrams:
s = '-'.join(word)
if s in d:
d[s] += 1
else:
d[s] = val
You could use the tuples in the list directly as dictionary keys -- you do not need to join them to a single string. In Python 2.7, this gets particularly convenient in combination with collections.Counter
:
from collections import Counter
bigrams = [('wealth', 'gain'), ('gain', 'burnt'),
('burnt', 'will'), ('will', 'fire')]
counts = Counter(bigrams)
print counts
prints
Counter({('gain', 'burnt'): 1, ('will', 'fire'): 1, ('wealth', 'gain'): 1, ('burnt', 'will'): 1})
You should make yourself familiar with list comprehension. That makes the transformation of the first list easier:
bigrams = [x+"-"+y for x,y in bigrams]
Now have a look at the setdefault method of dict and use it like this:
data = {} # dict is build in, so don't use it as variable name
for bigram in bigrams:
data[bigram] = data.setdefault(bigram,0) + 1
If you want to have an even more compressed version, you might look at the itertools module.
try this:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
bigram_dict = {}
for bigram in bigrams:
key = '-'.join(bigram)
if key in bigram_dict:
bigram_dict[key] += 1
else:
bigram_dict[key] = 1
also, I feel obliged to point out that these are not bigrams in any way, shape or form. I'm not sure exactly what you mean to say, but they're certainly not bigrams!
精彩评论