代码如下:
#encoding=utf-8
print '中国'
#获取一个字典的子集
print '---列表推导'
#不修改原来的字典 列表推导
def sub_dict(somedict,somekeys,default=None):
return dict([(k,somedict.get(k,default)) for k in somekeys])
dict1={1:2,3:4,6:7,9:10}
somekeys=(1,9)
print sub_dict(dict1,somekeys)
print dict1
#修改原来的字典 列表推导
def sub_dict_remove(somedict, somekeys, default=None):
return dict([(k,somedict.pop(k,default)) for k in somekeys])
print sub_dict_remove(dict1,somekeys)
print dict1
print '---生成器表达式'
#不修改原来的字典 生成器表达式
def sub_dict2(somedict,somekeys,default=None):
return dict((k,somedict.get(k,default)) for k in somekeys)
dict1={1:2,3:4,6:7,9:10}
somekeys=(1,9)
print sub_dict2(dict1,somekeys)
print dict1
#修改原来的字典 生成器表达式
def sub_dict_remove2(somedict, somekeys, default=None):
return dict((k,somedict.pop(k,default)) for k in somekeys)
print sub_dict_remove2(dict1,somekeys)
print dict1
打印结果如下:
中国
{1: 2, 9: 10}
{1: 2, 3: 4, 6: 7, 9: 10}
{1: 2, 9: 10}
{3: 4, 6: 7}
{1: 2, 9: 10}
{1: 2, 3: 4, 6: 7, 9: 10}
{1: 2, 9: 10}
{3: 4, 6: 7}