Saturday, August 1, 2015

Python: dictionary (3)

Abstract: intersects, merge, and minus dictionary

The script:
# -*- coding: utf-8 -*-
"""
Created on Sat Aug  1 17:31:40 2015

@author: yuan
"""

d1={'g':3, 'a':12,'b':2,'c':32,'d':120,'e':102,'f':112}

d2={'i':13, 'a':12,'b':2,'k':232,'s':70,'e':102,'g':72}

#intersects of two dictionaries
d12={}
print 'method1:'
for k1 in d1.keys():
    if d2.has_key(k1):
        d12[k1]=d1[k1]
print d12

print '\nmethod2:'
print "Intersects:", filter(d1.has_key, d2.keys())

#merge
print 'merge two dictionaries:'
d12={}
d12.update(d1)
d12.update(d2)
print d12

#minus
print 'Of the items in d1, remove those in d2 '
d3=[k for k in d1.keys() if not d2.has_key(k)]
print d3

No comments:

Post a Comment