简体   繁体   中英

Trie Displaying in Python

Hi I just started to try out Trie in Python. I have a code like this but when I get the output, I don't know how to convert it back to a normal list or dictionary.

Input:

TestDict = {0: {"ItemName" : "washing machine", "ItemStockLevel" : 15, "ItemCostPrice" : 129.21, "ItemSellingPrice" : 142.21},  
                1: {"ItemName": "french fries", "ItemStockLevel": 100, "ItemCostPrice": 21.51, "ItemSellingPrice": 41.77},  
                2: {"ItemName" : "magnum ice cream", "ItemStockLevel" : 30, "ItemCostPrice" : 57.32, "ItemSellingPrice" : 78.31}}

test = []  
for key in TestDict:  
    test.append(TestDict[key]["ItemName"])

_end = '_end_'  
def make_trie(list):  
   root = dict()  
   for word in list:  
       current_dict = root  
       for letter in word:  
           current_dict = current_dict.setdefault(letter, {})  
       current_dict[_end] = _end  
   return root  
print(make_trie(test))

Output:

{'w': {'a': {'s': {'h': {'i': {'n': {'g': {' ': {'m': {'a': {'c': {'h': {'i': {'n': {'e': {'_end_': '_end_'}}}}}}}}}}}}}}}, 'f': {'r': {'e': {'n': {'c': {'h': {' ': {'f': {'r': {'i': {'e': {'s': {'_end_': '_end_'}}}}}}}}}}}}, 'm': {'a': {'g': {'n': {'u': {'m': {' ': {'i': {'c': {'e': {' ': {'c': {'r': {'e': {'a': {'m': {'_end_': '_end_'}}}}}}}}}}}}}}}}}

Want to get:

{"washing machine", "french fries", "magnum ice cream"}

using the Output above.

  • Try this
TestDict = {0: {"ItemName" : "washing machine", "ItemStockLevel" : 15, "ItemCostPrice" : 129.21, "ItemSellingPrice" : 142.21},  
                1: {"ItemName": "french fries", "ItemStockLevel": 100, "ItemCostPrice": 21.51, "ItemSellingPrice": 41.77},  
                2: {"ItemName" : "magnum ice cream", "ItemStockLevel" : 30, "ItemCostPrice" : 57.32, "ItemSellingPrice" : 78.31}}

test = []  
for key in TestDict:  
    test.append(TestDict[key]["ItemName"])

_end = '_end_'  
def make_trie(list):  
   root = []
   for word in list:  
       root.append(word)
   return root  
print(set(make_trie(test)))

  • output
{'magnum ice cream', 'french fries', 'washing machine'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM