On 2011/11/25 10:41 AM, lina wrote:
pairs
{('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25}
such as here ('66', '69') and ('69', '66') is one key,
I wanna keep only one and add the value of those two keys, above is a
very simple example:
here is the (failed) code:
for k, v in pairs.items():
if str(k)[1]+str(k)[0] in pairs.keys():
print(pairs[str(k)[1]+str(k)[0]])
pairs[k]+=pairs[str(k)[1]+str(k)[0]]
del pairs[str(k)[1]+str(k)[0]]
print(v,k)
Thanks for any advice,
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
pairs.items() is fine if it's a small dictionary but for larger ones
it's going to slow things down as it generates the entire list of items
before you continue, rather use .iteritems() as it creates an iterator
which only yields one item at a time making it more efficient.
str(k)[1]+str(k)[0] is string concatenation so your first key tested is
'6669' and not ('66', '69') as you intended, you would have to create a
new tuple to get the key you wanted like `if (k[1], k[0]) in
pairs.keys():`. Also, your check to "in pairs.keys()" is wasteful as you
generate a new list of keys for every key and you will be better off
using `in pairs:` directly as it performs a dictionary lookup to test if
the key exists.
With that in mind, this is how I would re-write that code segment. YMMV
for key in pairs.iterkeys():
# The [::-1] creates a reverse of the iterable so ('66', '69') will
be ('69', '66')
if key[::-1] in pairs:
try:
# The first instance of the pair gets kept and the reversed
gets added
pairs[key] += pairs[key[::-1]]
del pairs[::-1]
except KeyError:
print "Key ('%s', '%s') already accumulated)" % key
Hope that helps.
--
Christian Witts
Python Developer
//
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor