Py学习  »  Python

Python如何在字典中针对单个键创建多个值

Zahid • 3 年前 • 1207 次点击  

[Python,datastructres]如何在字典中针对单个键创建多个值,如下所示

main_dict = { 'stats': IP_dict_name_1, 'Add': IP_dict_name_2}  
IP_dict_name_1 = {uniq_ip_1 : [time, threshold_counter], unique_ip_2: [time, threshold_counter]}  
IP_dict_name_1 = {uniq_ip_1 : [time, threshold_counter], unique_ip_2: [time, threshold_counter]}  

实际上,我想创建一个数据结构,在这个结构中,我们可以像上面的场景那样记录命令。例如,如果“stats”命令已经插入到字典中,那么它不会再次插入字典中。如果不存在,那么创建上面的数据结构。我不知道如何有效地做到这一点。总之,我想跟踪每个执行命令的远程ip,并设置命令阈值,即5如果他想在一小时内执行“stats”命令超过3次,则不允许这样做。有人能帮忙吗。有什么好主意吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128235
 
1207 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Tzane
Reply   •   1 楼
Tzane    3 年前

您可以检查密钥是否已存在于中 main_dict 具有 if "stats" not in main_dict ,只需将“stats”替换为您想要检查的任何键即可。下面是一个简单的片段:

command = {
    "uniq_ip_1" : ["time", "threshold_counter"],
    "unique_ip_2": ["time", "threshold_counter"]}

main_dict = {}

if "stats" not in main_dict:
    main_dict["stats"] = command

print(main_dict)

if "stats" not in main_dict:
    main_dict["stats"] = command

print(main_dict)
Stef
Reply   •   2 楼
Stef    3 年前

你可以用成对的 (command, ip) 作为你的日志字典的钥匙。

另外,我推荐最好的 dictionary method dict.setdefault .

exec_logs = {}
threshold_per_hour = 3

def exec_command(command_name, ip, current_hour):
  previous_hour, n = exec_logs.setdefault((command_name, ip), (current_hour, 0))
  if previous_hour == current_hour:
    if n >= threshold_per_hour:
      print('Command aborted: User {} cannot execute command {} more than {} times per hour.'.format(ip, command_name, threshold_per_hour))
      return # do not execute command
    else:
      exec_logs[(command_name, ip)] = (current_hour, n+1)
      print('Command {} successfully executed.'.format(command_name))
  else:
    exec_logs[(command_name, ip)] = (current_hour, 1)
    print('Command {} successfully executed.'.format(command_name))

测试:

>>> exec_command('make coffee', 127, '1pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 127, '1pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 127, '1pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 127, '1pm')
Command aborted: User 127 cannot execute command make coffee more than 3 times per hour.
>>> exec_logs
{('make coffee', 127): ('1pm', 3)}
>>> exec_command('make coffee', 127, '2pm')
Command make coffee successfully executed.
>>> exec_logs
{('make coffee', 127): ('2pm', 1)}
>>> exec_command('make coffee', 139, '2pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 139, '2pm')
Command make coffee successfully executed.
>>> exec_command('make coffee', 139, '2pm')
Command make coffee successfully executed.
>>> exec_logs
{('make coffee', 127): ('2pm', 1), ('make coffee', 139): ('2pm', 3)}