如何在现有词典中添加词典,Python

How can I add a dictionary inside an existing dictionary ,Python

我有下面的脚本,其中我有字典 dd[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"]}

通过示例回答您的问题,这是将 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 是您的列表。

您可以使用 dict.items() 方法获得 (key, value)tuples

你可以这样做:

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