Python教程-python字典中key的灵活使用fromkeys()

#coding:utf-8
#http://www.cnblogs.com/yangyongzhi/archive/2012/09/17/2688326.html
#有两个随机生成的字典dict_a和dict_b,找出这两个字典的元素中value相同的元素,并把这些value做为key值,
#该key对应的新value值通过调用提供的get_current_time函数获取,然后把该对key-value赋值给空字典dict_c
import random
import time
dict_a={0:'t',1:'h',2:'j',3:'y',4:'e'}
dict_b={0:'y',1:'d',2:'h',3:'s',4:'v'}

def get_current_time():
    time.sleep(1)
    return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())

def random_dict():
    rand_dict = dict.fromkeys(range(5))
    for key,value in rand_dict.items():
        rand_dict[key]=chr(random.randint(97,122))
    return rand_dict

dict_a=random_dict()
dict_b=random_dict()

print dict_a
print dict_b

dict_c={}

dict_a_values=dict_a.values()
dict_b_values=dict_b.values()
print dict_a_values
print dict_b_values

dict_combine=[a for a in dict_a_values if a in dict_b_values]

if len(dict_combine)>0 :
    dict_c=dict.fromkeys(dict_combine,get_current_time())
    print dict_c

elif len(dict_combine)==0:
    print '两个字典的元素中不存在value相同的元素'

'''1 初始化
>>> d = dict(name='visaya', age=20)
>>> d = dict(zip(['name', 'age'], ['visaya', 20]))

#dict.fromkeys(listkeys, default=0) 把listkeys中的元素作为key均赋值为value,默认为0
>>> d = dict.fromkeys(['a', 'b'], 1)
>>> d
{'a': 1, 'b': 1}'''

 

转载于:https://my.oschina.net/CeShiXiaoSongShu/blog/804987

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值