2016-06-06 2 views
0

디렉토리의 모든 파일에서 문자열을 가져 와서 어떻게 든 기록해야하므로 defaultdict를 사용하여 만들려고했지만 점진적으로 사전의 각 레이어에 추가하는 방법을 찾는 데 어려움이 있습니다.파이썬 : defaultdict (dict) 어떻게 중첩 된 사전을 만들 수 있습니까?

파일 이름

번들

정보

번들

정보 : 기본적으로, 어떤 사전이 같이해야 할 것은 이것이다

파일 이름

번들

정보

등 나는 목록 그래서 내가 할 수와 같은 정보를 가지고 필자가 필요로하는 것만을 목록에 추가 할 수 있지만 여기에있는 것을 실행할 때 각 파일 이름에 대해 단일 번들 및 정보를 얻게됩니다. update() 함수가 내부의 값을 대체하는 것처럼 보입니다. 그리고 계속 추가하고 각 번들에 대해 최신 사전을 만드는 방법을 모르겠습니다. 어떤 도움도 감사하고 혼란스러워서 죄송합니다.


import collections 
import os 

devices = collections.defaultdict(lambda: collections.defaultdict(dict)) 
# bundles = collections.defaultdict(dict) 

for filename in os.listdir('.'): 
    if os.path.isfile(filename): 
     if '.net' in filename: 
      dev = open(filename) 

      for line in dev: 

       line = line.strip() 
       values = line.split(' ') 

       if values[0] == 'interface': 
        bundle_name = values[1] 
        if '/' in bundle_name: 
         pass 
        else: 
         if len(values) == 2: 
          ur_device = devices[filename] 
          ur_device.update(
           { 
            'bundle_name': bundle_name, 
            'bundle_info': [], 
           } 
          ) 

       if 'secondary' in values: 
        pass 
       elif values[0] == 'ipv4' and values[1] == 'address' and len(values) == 4: 
        ur_device['bundle_info'].append(
         { 
          'ip_address': values[2], 
          'subnet_mask': values[3], 
         } 
        ) 

      dev.close() 

답변

2

사전 적이 키와 값, 같은 키가 사전에 뭔가를 넣어 모든 시간이 뭔가, 그 값을 대체합니다. 예를 들어 :

dictionary = {} 
# Insert value1 at index key1 
dictionary["key1"] = "value1" 

# Overwrite the value at index key1 to value2 
dictionary["key1"] = "value2" 

print(dictionary["key1"]) # prints value2 

이 코드에 대해 이해가되지 않는 몇 가지가 있지만 그 사용되는 난 당신이 실제로 사전 (대신 업데이트 방법에 물건을 추가하는 위의 구문을 사용하는 것이 좋습니다 사전에 키/값 쌍 목록 추가).

내가 함께 # 코드에 몇 가지 제안을 표시 아래 **의, 각 파일 이름에 대해 여러 번들이 필요

import collections 
import os 

#** I'm guessing you want to put your devices into this dict, but you never put anything into it 
devices = collections.defaultdict(lambda: collections.defaultdict(dict)) 
# bundles = collections.defaultdict(dict) 

for filename in os.listdir('.'): 
    if os.path.isfile(filename): 
     if '.net' in filename: 
      dev = open(filename) 

      for line in dev: 

       line = line.strip() 
       values = line.split(' ') 
       #** declare bundle_name out here, it is better form since we will make use of it in the immediate scopes below this 
       bundle_name = '' 

       if values[0] == 'interface': 
        bundle_name = values[1] 
        if '/' in bundle_name: 
         pass 
        else: 
         if len(values) == 2: 
          #** This is assuming you populated devices somewhere else?? 
          devices[filename][bundle_name] = [] 

       if 'secondary' in values: 
        pass 
       elif values[0] == 'ipv4' and values[1] == 'address' and len(values) == 4: 
        #** ur_device was not declared in this scope, it is a bad idea to use it here, instead index it out of the devices dict 
        #** it also might be worth having a check here to ensure devices[filename] actually exists first 
        devices[filename][bundle_name].append(
         { 
          'ip_address': values[2], 
          'subnet_mask': values[3], 
         } 
        ) 

      dev.close() 

** 편집 **

질문에서 찾고있다. 그러나 사전 구조가 상세하지 않고 데이터로 장치를 초기화하는 방법에 대한 코드를 제공하지 않는 것 같습니다.

기본적으로 어떤 값만이 아니라 사전의 각 레벨에 어떤 키가 있는지 생각해야합니다.

디바이스 (파일 이름 : 디바이스)
디바이스 (bundle_name?: 정보) < - 당신은 당신에 대한 세부 사항을 추가이 사전
정보 (목록) 누락

난 당신의 의도에 대한 나의 추측으로 위의 코드를 변경했습니다.

+0

통찰력을 가져 주셔서 감사합니다! 나는 그것이 작동하도록 끝내었고, 당신의 의견은 그것을 단순화하는 데 도움이되었습니다. – dreamville

관련 문제