项目作者: alphatwirl

项目描述 :
Attribute-access ordered dictionary in Python
高级语言: Python
项目地址: git://github.com/alphatwirl/atdict.git
创建时间: 2019-02-23T10:19:02Z
项目社区:https://github.com/alphatwirl/atdict

开源协议:BSD 3-Clause "New" or "Revised" License

下载


PyPI version
Anaconda-Server Badge
DOI
Test Status
codecov

atdict

An attribute-access ordered dictionary


atdict is an attribute-access ordered dictionary. You can use a key
name as an attribute to access the value of the dictionary for a key,
for example, o.key_name rather than o['key_name']. Only a minimum
set of methods are implemented so as to minimize the chances of name
conflicts.



Requirement

  • Python 3.6, 3.7, 3.8, or 3.9

Install

You can install with conda from conda-forge:

  1. conda install -c conda-forge atdict

or with pip:

  1. $ pip install -U atdict

How to use

Import atdict

Import atdict from the package atdict.

  1. from atdict import atdict

Initialize atdict

You can initialize an atdict with any arguments that can initialize
collections.OrderedDict.

For example:

  1. o1 = atdict([('foo', 40), ('bar', 'ham')])
  2. print(o1)

It will print.

  1. atdict(foo=40, bar='ham')

An atdict can be also initialized with another atdict.

  1. o2 = atdict(o1)
  2. print(o2)

The o2 is initialized with a (shallow) copy of the contents of o1.

  1. atdict(foo=40, bar='ham')

Access to a value

Yon can use a key name as an attribute of atdict.

  1. print(o1.foo)

This will print the value for the key foo, which is 40.

  1. 40

Modify a value

To modify a value, you can assign a new value to the attribute.

  1. o1.foo = 50
  2. print(o1)
  1. atdict(foo=50, bar='ham')

The value for the key foo changed from 40 to 50.

Add a key

To add a key, you can also assign a value to the attribute

  1. o1.baz = 'eggs'
  2. print(o1)
  1. atdict(foo=50, bar='ham', baz='eggs')

Delete a key

del deletes a key.

  1. del o1.bar
  2. print(o1)
  1. atdict(foo=50, baz='eggs')

Copy and deepcopy

A copy will be created if atdict is initialized with another
atdict. However, this will be a shallow copy.

  1. l = [1, 2]
  2. o1 = atdict([('foo', l)])
  3. o2 = atdict(o1)
  4. print(o2.foo is o1.foo)
  1. True

To make a deep copy, you can use copy.deepcopy().

  1. import copy
  2. l = [1, 2]
  3. o1 = atdict([('foo', l)])
  4. o2 = copy.deepcopy(o1)
  5. print(o2)
  1. atdict(foo=[1, 2])

o2.foo and o1.foo are not the same object.

  1. print(o2.foo is o1.foo)
  1. False

Pickle

An atdict is picklable as long as all values are picklable.

  1. import pickle
  2. o1 = atdict([('foo', 40), ('bar', 'ham')])
  3. p1 = pickle.dumps(o1)
  4. o2 = pickle.loads(p1)
  5. print(o2)
  1. atdict(foo=40, bar='ham')

License

  • atdict is licensed under the BSD license.

Contact