我有以下脚本,其中我的词典d
包含d[domain]
日期,dns_dic
词典以domain
为键,rdata = ip
为值。
Expected result:
我想知道如何将字典dns_dic
的密钥作为域的tuple
,日期(字典d的键值)和dns_dic
的值ip
,像
dns_dic = {(domain1,date1):ip1,(domain2,date2):ip2}
等。
dns_dic = defaultdict(set)
d = {domain1:date1,domain2:date2, ..}
if domain in d:
for i in d[domain]:
if jdata.get('time_first') <= i <= jdata.get('time_last'):
dns_dic[dom].update(jdata.get('rdata', []))
这就是jdata
的样子:
{"rrname":"c.000a.biz.","time_last":1400243400,"time_first":1388645949,"rdata":["50.21.180.100"]}
{"rrname":"c.000a.biz.","time_last":1389133600,"time_first":1389133600,"rdata":["50.21.180.100"]}
{"rrname": "0001211.com.","time_last":1407101755,"time_first":1389074193,"rdata":["50.21.180.100"]}
答案 0 :(得分:2)
通过示例回答您的问题,这是将tuple
添加为dict
密钥的简单方法:
# create a dict
d = {}
# add tuple as key with some value
d[('some domain', 'some date')] = 'some ip'
print d
输出:
{('some domain', 'some date'): 'some ip'}
要将list
转换为tuple
使用tuple(lst)
,其中lst
是您的列表。
答案 1 :(得分:0)
您可以使用tuples
方法获得(key, value)
dict.items()
。
for item in d.items(): # item is (key,value) tuple
domain,date = item
for jd in jdata:
if jd.get('time_first') <= date <= jd.get('time_last'):
dns_dic[item] = jd.get('rdata',[])
假设变量类似于
dns_dic = {}
d = {"domain1":1389074195,"domain2":1388645951,"domain3":1389133601}
jdata = [
{"rrname":"c.000a.biz.","time_last":1400243400,"time_first":1388645949,
"rdata":["50.21.180.100"]},
{"rrname":"c.000a.biz.","time_last":1389133600,"time_first":1389133600,
"rdata":["50.21.180.100"]},
{"rrname": "0001211.com.","time_last":1407101755,"time_first":1389074193,
"rdata":["50.21.180.100"]},
]