2013-12-10 43 views
0

說我有這本字典:半拼合字典

"pools": { 
     "JP": { 
      "longName": "Jackpot", 
      "poolTotal": 318400, 
      "shortName": "Jpot", 
      "sortOrder": 9 
     } 
    }, 

我怎麼會輸出這個,所以我有這樣的:

pool_JP_longname: Jackpot 
pool_JP_poolTotal: 318400 
etc 
etc 

嵌套不應該被限制在2或3級,所以它應該是通用的。

或者又如:

{ 
    "soccer": { 
     "X07": { 
      "date": "2013-11-22", 
      "poolType": "S10", 
      "code": "INT", 
      "closeTime": "20:00:00", 
      "poolStatus": "OP", 
      "pool": { 
       "1": { 
        "startRace": 1, 
        "matchs": { 
         "1": { 
          "teamA": "Ajax Cape Town", 
          "teamB": "Moroka Swallows", 
          "matchStatus": "OP" 
         }, 
         "2": { 
          "teamA": "Bidvest Wits", 
          "teamB": "MP Black Aces", 
          "matchStatus": "OP" 
         } 
        } 
       } 
      } 
     } 
    } 
} 

應該是這樣的:

soccer_X07_data: "2013-11-22" 
soccer_X07_poolType: "S10" 
etc 
soccer_X07_pool_1_matchs_1_teamA 
soccer_X07_pool_1_matchs_1_teamB 
etc 

,我已經開始做這樣的,但是這是不正確的:

def iterTool(json_data, key_string): 
    for root_key, item in sorted(json_data.items(), key=itemgetter(0)): 
     if type(json_data[root_key]) == dict: 
      key_string += "_%s" % root_key 
      if json_data[root_key].keys(): 
       for parent_key in json_data[root_key]: 
        if type(json_data[root_key][parent_key]) in [unicode]: 
         print "%s_%s" % (key_string, parent_key) 
         # print key_string.split("_") 
         # pass 
      iterTool(json_data[root_key], key_string) 

這像這樣輸出:

_soccer_X07_code 
_soccer_X07_poolStatus 
_soccer_X07_closeTime 
_soccer_X07_poolType 
_soccer_X07_date 
_soccer_X07_pool_1_matchs_1_matchStatus 
_soccer_X07_pool_1_matchs_1_teamA 
_soccer_X07_pool_1_matchs_1_teamB 
_soccer_X07_pool_1_matchs_1_10_matchStatus 
_soccer_X07_pool_1_matchs_1_10_teamA 
_soccer_X07_pool_1_matchs_1_10_teamB 
_soccer_X07_pool_1_matchs_1_10_2_matchStatus 
_soccer_X07_pool_1_matchs_1_10_2_teamA 
_soccer_X07_pool_1_matchs_1_10_2_teamB 
_soccer_X07_pool_1_matchs_1_10_2_3_matchStatus 
_soccer_X07_pool_1_matchs_1_10_2_3_teamA 
_soccer_X07_pool_1_matchs_1_10_2_3_teamB 
_soccer_X07_pool_1_matchs_1_10_2_3_4_matchStatus 
_soccer_X07_pool_1_matchs_1_10_2_3_4_teamA 
_soccer_X07_pool_1_matchs_1_10_2_3_4_teamB 
_soccer_X07_pool_1_matchs_1_10_2_3_4_5_matchStatus 
_soccer_X07_pool_1_matchs_1_10_2_3_4_5_teamA 
... 

現在只是一個弧線球..

讓說,字典是這樣的:

{ 
    "CAP": { 
     "countryName": "ZAF", 
     "displayName": "AN" 
    }, 
    "SPA": { 
     "countryName": "AUs", 
     "displayName": "AG" 
    } 
} 

然後它不會是有意義的壓平,而是:

GENERIC_KEY:CAP,國家名稱: ZAF,displayName:AN

您會如何檢測此?

+0

您的「曲線球」是一個單獨的問題 – jonrsharpe

+0

當然,我會在單獨的問題中提出這個問題。謝謝您的幫助 – Harry

回答

2

這將遞歸壓扁你的字典:

def flatten_dict(dct, output=None, prefix=None): 
    if output is None: 
     output = {} 
    if prefix is None: 
     prefix = [] 
    for key in dct: 
     if isinstance(dct[key], dict): 
      flatten_dict(dct[key], output, prefix + [key]) 
     else: 
      output["_".join(prefix + [key])] = dct[key] 
    return output 

對於你的第二個例子,我得到:

{'soccer_X07_pool_1_matchs_2_teamA': 'Bidvest Wits', 
'soccer_X07_pool_1_matchs_2_teamB': 'MP Black Aces', 
'soccer_X07_pool_1_matchs_1_matchStatus': 'OP', 
...} 
1

一個簡單的解決辦法是這樣的:

d = { ... } 

def flatten(dic, stack=None): 
    if not stack: stack = [] 
    for key,value in dic.iteritems(): 
     new_stack = stack[:] + [key] 
     if isinstance(value, dict): 
      for result in flatten(value, new_stack): 
       yield result 
     else: 
      yield new_stack, value 

# just print it:   
for stack, value in flatten(d): 
    print '{}: {}'.format('_'.join(stack), value) 

# create a new dict: 
new_d = {'_'.join(stack): value for stack, value in flatten(d)} 
0

這是一個基本的遞歸問題(或者一個可以用遞歸解決的問題):

這裏是滿足你的第一個例子(一個人爲的例子或多或少):

d = { 
    "pools": { 
     "JP": { 
      "longName": "Jackpot", 
      "poolTotal": 318400, 
      "shortName": "Jpot", 
      "sortOrder": 9 
     } 
    } 
} 


def flattendict(d): 
    for k, v in d.items(): 
     if isinstance(v, dict): 
      for x in flattendict(v): 
       yield "{}_{}".format(k, x) 
     else: 
      yield "{}_{}".format(k, v) 


for item in flattendict(d): 
    print item 

注:我已經離開幾個問題爲您解決問題和調查。