二维dict作业未达到预期

2024-04-26 00:43:03 发布

您现在位置:Python中文网/ 问答频道 /正文

函数的返回未达到预期。你知道吗

我的环境py2.7.11 centos6.5。你知道吗

我希望函数返回这样的返回

{'www.baidu.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1}, 
'www.google.com': {'3xx': 0, 'response_time': 0, '5xx': 0, '4xx': 0}}

但事实上是这样的回报。不应分配send_dict['www.google.com']['response_time']send_dict['www.google.com']['response_code']。但为什么呢?你知道吗

{'www.baidu.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1}, 
'www.google.com': {'3xx': 0, 'response_time': 0.126, '5xx': 0, '4xx': 1}}

Python代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

sink_dict = {'sink_zabbix_monitor_keys': '3xx,4xx,5xx,response_time',
             'sink_zabbix_domain_keys': 'www.baidu.com,www.google.com'}
sub_send_dict = dict.fromkeys(sink_dict['sink_zabbix_monitor_keys'].split(','), 0)
send_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), sub_send_dict)


def calculate_item(item):

    response_code_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), 0)
    response_time_dict = dict.fromkeys(sink_dict['sink_zabbix_domain_keys'].split(','), 0)
    domain = item['domain']
    response_code_dict[domain] = int(item['response_code'])
    response_time_dict[domain] = float(item['response_time'])
    if domain in send_dict:
        print domain
        if response_time_dict[domain] > float(send_dict[domain]['response_time']):
            send_dict[domain]['response_time'] = response_time_dict[domain]
        send_dict[domain][str(response_code_dict[domain])[0] + "xx"] += 1
    return send_dict

tmp_item = {'domain': 'www.baidu.com', 'response_time': '0.126', 'response_code': '401'}
tmp_item1 = {'domain': 'www.google.com', 'response_time': '0.126', 'response_code': '401'}
tmp_item2 = {'domain': 'www.baidu.com', 'response_time': '0.166', 'response_code': '401'}

print calculate_item(tmp_item)

Tags: comsendtimeresponsedomainwwwgooglecode
1条回答
网友
1楼 · 发布于 2024-04-26 00:43:03

给你:

send_dict = {k: sub_send_dict.copy() for k in sink_dict['sink_zabbix_domain_keys'].split(',')}

这叫做听写理解。这是因为我将字典的shallow copy分配给键。dict.fromkeys()将值赋给每个键,所有键将共享相同的sub_send_dict引用。你知道吗

从(链接的)python文档:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

相关问题 更多 >

    热门问题