如何在现有字典Python中添加字典

时间:2015-02-03 09:14:29

标签: python dictionary key

我有以下脚本,其中我的词典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"]}

2 个答案:

答案 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"]},
 ]