具有递归点符号存取的Python词典 – Box

具有递归点符号存取的Python词典。

from box import Box

my_box = Box(
    {"owner": "Mr. Powers",
     "contents": [{"qty": 1, "item": "blue crushed-velvet suit"},
                  {"qty": 1, "item": "frilly lace crava"},
                  {"qty": 1, "item": "gold medallion with peace symbol"},
                  {"qty": 1, "item": "Swedish-made enlarger pump"},
                  {"qty": 1, "item": "credit card receipt for Swedish-made enlarger pump, "
                                     "signed Austin Powers."},
                  {"qty": 1, "item": "warranty card for Swedish-made enlarger pump, "
                                     "filled out by Austin Powers."},
                  {"qty": 1, "item": "book, Swedish-Made Enlarger Pumps and Me"}],
     "affiliates": {
         "Vanessa": "Sexy",
         "Dr Evil": "Not groovy",
         "Scott Evil": "Doesn't want to take over family business"}
    })

my_box.affiliates.Vanessa == my_box['affiliates']['Vanessa']

my_box.contents[0].item
'blue crushed-velvet suit'

# Here's something that no other library supports (that I know of)
# Automatic creation of Boxes in sub-lists
my_box.contents.append({"qty": 1, "item": "tie-dyed socks"})
my_box.contents[-1].item
'tie-dyed socks'

# Box object is callable, and returns a tuple of available keys
my_box()
('owner', 'contents', 'affiliates')

my_box.funny_line = "They tried to steal my lucky charms!"

my_box['funny_line']
'They tried to steal my luck charms!'

my_box.credits = {'Austin Powers': "Mike Myers", "Vanessa Kensington": "Elizabeth Hurley"}
# <Box: {'Austin Powers': 'Mike Myers', 'Vanessa Kensington': 'Elizabeth Hurley'}>

my_box.to_yaml()  # .to_json() also available
# owner: Mr. Powers
# affiliates:
#   Dr Evil: Not groovy
#   Scott Evil: Doesn't want to take over family business
#   Vanessa: Sexy
# contents:
# - item: blue crushed-velvet suit
#   qty: 1
# - item: frilly lace crava
#   qty: 1
# - item: gold medallion with peace symbol
#   qty: 1
# ...

安装

pip install python-box

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:具有递归点符号存取的Python词典 – Box