如何在Perl中将多键哈希在Python中实现为嵌套词典?

问题描述 投票:2回答:2

我有一些基本的代码来处理Perl哈希,我可以在这里解决以下元素:$ data {“WV2”} {789} {PP1}(或在作业中使用实际文本)...但我想使用Python词典做类似的事情。

Perl和Python中的一些简单程序说明了我一直在尝试复制的内容如下: -

所以,Perl代码: -

# hash.pl

use strict;
use warnings;

use Data::Dumper;

my %data = ();

my @reg_list = ( "MC1", "CA2", "WV2" );
my @site_list = ( 123, 456, 391, 287 );

$data{MC1}{4564}{PP}{1} = "-15,-15C";
$data{MC1}{4564}{PP}{2} = "5,5C";
$data{MC1}{4564}{PP}{3} = "-19,-19C";
$data{MC1}{4564}{PP}{4} = "-12,-12C";

printf("---- One:\n");
print Dumper(%data);                 # Ok, shows the full strucure

printf("---- Two:\n");
print Dumper($data{"MC2"});          # Shows as undef (sensible)

printf("---- Three:\n");
print Dumper($data{"MC1"});          # Ok, showing the key:values for each "site" key

printf("---- Four:\n");
print Dumper($data{"MC1"}{"4564"});  # Ok, shows the actual equality value above


# ---- This works Ok

my %xdata = ();
$xdata{"MC1"}{123}{"PP"} = "-15,-15C";
$xdata{"MC1"}{456}{"PP"} = "5,5C";
$xdata{"MC1"}{391}{"PP"} = "-19,-19C";
$xdata{"MC1"}{287}{"PP"} = "-12,-12C";

printf("---- One:\n");
print Dumper(%xdata);                # Ok, shows the full strucure


#pprint.pprint(data["MC2"]) 
#pprint.pprint(data["MC1"}{391]) 


# [eof]

......和Python代码: -

# dict.py

import pprint
import collections

reg_list  = [ "MC1", "CA2", "WV2" ]
site_list = [ 123, 456, 391, 287 ]

#data = {}
data = collections.defaultdict(dict) # {}
data["MC1"][123] = "-15,-15C"
data["MC1"][456] = "5,5C"
data["MC1"][391] = "-19,-19C"
data["MC1"][287] = "-12,-12C"

print("---- One:")
pprint.pprint(data)              # Ok, shows the full strucure

print("---- Two:")
pprint.pprint(data["MC2"])       # Shows: {} [...Ok, undefined...]

print("---- Three:")
pprint.pprint(data["MC1"])       # Ok, showing the key:values for each "site" key

print("---- Four:")
pprint.pprint(data["MC1"][391])  # Ok, shows the actual equality value above

# ---- Cannot get the following to work

xdata = collections.defaultdict(dict) # {}
xdata["MC1"][123]["PP"] = "-15,-15C"  # ERROR: Key error 123
xdata["MC1"][456]["PP"] = "5,5C"
xdata["MC1"][391]["PP"] = "-19,-19C"
xdata["MC1"][287]["PP"] = "-12,-12C"

#pprint.pprint(data["MC2"]) 
#pprint.pprint(data["MC1"][391]) 

# [eof]

每个计划的产出如下: -

# Perl Output:

---- One:
$VAR1 = 'MC1';
$VAR2 = {
          '4564' => {
                      'PP' => {
                                '4' => '-12,-12C',
                                '1' => '-15,-15C',
                                '3' => '-19,-19C',
                                '2' => '5,5C'
                              }
                    }
        };
---- Two:
$VAR1 = undef;
---- Three:
$VAR1 = {
          '4564' => {
                      'PP' => {
                                '4' => '-12,-12C',
                                '1' => '-15,-15C',
                                '3' => '-19,-19C',
                                '2' => '5,5C'
                              }
                    }
        };
---- Four:
$VAR1 = {
          'PP' => {
                    '4' => '-12,-12C',
                    '1' => '-15,-15C',
                    '3' => '-19,-19C',
                    '2' => '5,5C'
                  }
        };
---- One:
$VAR1 = 'MC1';
$VAR2 = {
          '391' => {
                     'PP' => '-19,-19C'
                   },
          '456' => {
                     'PP' => '5,5C'
                   },
          '123' => {
                     'PP' => '-15,-15C'
                   },
          '287' => {
                     'PP' => '-12,-12C'
                   }
        };

......并从Python: -

# Python Output:-

---- One:
defaultdict(<class 'dict'>,
            {'MC1': {123: '-15,-15C',
                     287: '-12,-12C',
                     391: '-19,-19C',
                     456: '5,5C'}})
---- Two:
{}
---- Three:
{123: '-15,-15C', 287: '-12,-12C', 391: '-19,-19C', 456: '5,5C'}
---- Four:
'-19,-19C'
Traceback (most recent call last):
  File "C:\Projects\00-Development\LXQuery\CDB-Review\dict.py", line 30, in <module>
    xdata["MC1"][123]["PP"] = "-15,-15C"  # ERROR: Key error 123
KeyError: 123

我试图查找有关嵌套词典的信息......但是我所看到的一切并没有清楚地解释这个概念应该如何工作(无论如何我想到的)....特别是当有'使用中更深层次的词典。

我已经编写了大约25年的Perl代码,但我只是从Python开始。

在Windows 10 x64下运行ActiveState Perl v5.16.3,Build 1603和Anaconda Python 3.6.5。

非常感谢任何想法或建议。

python perl dictionary hash
2个回答
1
投票

Python不会像Perl对其哈希所做的那样自动生成多级词典。在第二级和更深级别,您必须在向其添加更多键之前将空dict分配给更高级别的dicts:

xdata = collections.defaultdict(dict)
xdata["MC1"] = collections.defaultdict(dict)
xdata["MC1"][123]["PP"] = "-15,-15C"  # ERROR: Key error 123
xdata["MC1"][456]["PP"] = "5,5C"
xdata["MC1"][391]["PP"] = "-19,-19C"
xdata["MC1"][287]["PP"] = "-12,-12C"

1
投票

解决问题的简单方法似乎是: -

xdata = collections.defaultdict(dict) # {}
xdata["MC1"][123] = {}                # Define the dict before using it
xdata["MC1"][123]["PP"] = "-15,-15C"  # Works Ok

......但这仍然意味着每当我发现'一个新的'价值'时,我必须'手动'定义一个字典... ...等等

尽管固有​​的Gotcha!有错误的打字和(可能的)dict内容的腐败,What is the best way to implement nested dictionaries?似乎是一个处理问题的好方法...特别是作为价值(在我当前的应用中,无论如何)“从来没有看到光明的一天“(它们是在进入我的应用程序之前生成并验证的机器)......所以,一些可能有用的代码可能是: -

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)() # retain local pointer to value
        return value                     # faster to return than 
                                         # ...'dict lookup'

ydata = Vividict()

ydata["MC1"][123]["PP"] = "-15,-15C"
ydata["MC1"][456]["PP"] = "5,5C"
ydata["MC1"][391]["PP"] = "-19,-19C"
ydata["MC1"][287]["PP"] = "-12,-12C"

pprint.pprint(ydata)              # Ok, shows the full strucure

感谢一堆建议和指针。

© www.soinside.com 2019 - 2024. All rights reserved.