Saravanan666/pypi-org huggingface dataset:
Package: dictmagic
dictmagicdictmagicis a very small python 3 package that makes it easier to do certain weird things with dictionaries.At the moment, it lets you convert to and from "flattened" dictionaries that use path syntax instead of nested dictionaries, and simplifies the process of accessing python dictionary elements as attributes. This package is mostly written to loading, saving, using, and coverting between various configuration methods easier.installationpip install dictmagicUsageusingdictmagic.pathsflattening and unflattening hierarchies of dicts lets you accessmydict['hello']['world']withmydict['hello/world']or vice versa. This is useful in contexts where having nested dicts is not practical (making hash maps that can be used in strictly typed languages, storing data in hdf5 attributes, etc)dictmagic.paths.flatten()ordictmagic.flatten()dictmagic.paths.unflatten()ordictmagic.unflatten()Overview(identical for both functions)in_dict: input dictionary. not modifiedsep: section separator (any char can be used,/is default)/in the style of unix, hdf5, and other things:in the style ofconfigparserfrom the standard library.in the style of YAMLusingpaths.flatten()Args:in_dict(dict): input (nested) dictionarysep(str, optional): separator between nested dicts. Defaults to '/'.except_nonstr_key(bool, optional): if True, raise exception if non-string key found. If False, converts key to string and proceeds. Defaults to True.Returns:dict: flattened dictionaryRaises:TypeError: if non-string key found (including in dup_key_repl)usingpaths.unflatten()Args:in_dict([type]): unput dictionarysep(str, optional): separator between nested paths inin_dict. Defaults to '/'.except_dup_key(bool, optional): if True, raise exception if a duplicate key is found. For behavior if False, see below. Defaults to True.dup_key_repl([type], optional): if exception is not raised, map duplicate to this value:
ifDcontains{ 'a' : 'val1', 'a/b' : 'val2' }thenunflatten(D)will have{ 'a' : { dup_key_repl : 'val1', 'b' : 'val2' } }Defaults to None.except_nonstr_key(bool, optional): if True, raise exception if non-string key found. If False, converts key to string and proceeds. Defaults to True.Raises:KeyError: ifexcept_dup_keyis True, raises key error when duplicate key foundTypeError: if non-string key found (including indup_key_repl)Returns:dict: nested dictionaryusingdictmagic.objdictmagic.obj.ObjectDictordictmagic.ObjectDictthis class, taking a single argumentdata, allows accessing elements of a that dictionary asobject.keyinstead ofobject['key'].why is this useful when you can just dump it intoobject.__dict__?
primarily because doing that will make copying your dict rather difficult without ending up with somewhat of a mess.miscoriginally developed by @mivanit for a config manager, then moved toknc-toolsfor a time. Check out that repo for more weird tools.PRs and feature requests welcome!you can find this project on PyPI:pypi.org/project/dictmagic/buildingto build the package:
(you probably don't need to do this unless you're uploading a fork to PyPI)python setup.py sdist bdist_wheel
Package: dictmapper
dictmapper was created to help transforming a sequence of python dictionaries to tabular format and specifically to transform json documents to be exported in csv fromat.UsageCreate a mapper:from dictmapper import Mapper, Mapping

class UserMapper(Mapper):

    user_id = Mapping('user_id')
    email = Mapping('email')
    Name = Mapping(lambda u: '%s %s' % (u['first_name'], u['last_name']), name='User Name')
    nickname = Mapping('nickname', default='N/A')
    street = Mapping('address/street')
    city = Mapping('address/city')
    joined_at = Mapping('joined_at', transform=lambda d: d.strftime('%Y-%m-%d'))Sample input:users_docs = [
    {
        'user_id': '1000001',
        'first_name': 'Test',
        'last_name': 'User',
        'email': 'user@test.com',
        'address': {
            'street': 'Example Road',
            'city': 'Emerald City',
        },
        'joined_at': datetime.now(),
    },
    {
        'user_id': '1000002',
        'first_name': 'Example',
        'last_name': 'Member',
        'nickname': 'exampy',
        'email': 'example@member.com',
        'address': {
            'street': 'Sample Road',
            'city': 'Emerald City',
        },
        'joined_at': datetime.now(),
    }
]Output:>>> mapper = UserMapper()
>>> mapper.headers()
['User id', 'Email', 'Name', 'Nickname', 'Street', 'City', 'Joined at']
>>> res = mapper.map(users_docs)
>>> res
[['1000001',
  'user@test.com',
  'Test User',
  'N/A',
  'Example Road',
  'Emerald City',
  '2012-03-18'],
 ['1000002',
  'example@member.com',
  'Example Member',
  'exampy',
  'Sample Road',
  'Emerald City',
  '2012-03-18']]Export to csvI recommend using the excellenttablib:import tablib
data = tablib.Dataset(*res, headers=mapper.headers())
data.csv
Package: dictmatch
dictmatchdictmatch：词典匹配工具
完整文档见README.mdGitHub:https://github.com/Bond-H/dictmatch安装说明代码对 Python 2/3 均兼容
- pip安装：pip install dictmatch- clone安装：先clone本代码库，然后运行python setup.py install- 手动安装：将 dictmatch 目录放置于当前目录或者 site-packages 目录，通过import dictmatch来引用
Package: dict-merger
Dict mergerSimple Cython+Python library for merge python dictionaries recursivelyPyPiUsagefromdict_merger.static_mergerimportmergea={1:2,2:3,3:{1:1,2:3},4:1,}b={1:5,3:{1:2},5:3,}merge(a,b)=={1:5,2:3,3:{1:2,2:3},4:1,5:3,}# P.S: If more than one given dict defines the same key,# then the one that is later in the argument sequence takes precedence.API# dict_merger.static_merger - pure Cython module with static python types# dict_merger.dynamic_merger - same module, but with dynamic types, works a bit slowerdefmerge(first_dict:dict,second_dict:dict)->dict:"""Merge 2 dicts recursively.If more than one given dict defines the same key,then the one that is later in the argument sequence takes precedence.:param first_dict: first dict to merge:param second_dict: second dict to merge:return: merged dict"""...defmerge_inplace(first_dict:dict,second_dict:dict)->None:"""Merge 2 dicts recursively.If more than one given dict defines the same key,then the one that is later in the argument sequence takes precedence.First dict will contain merged version, faster in general.:param first_dict: first dict to merge, will contain merged version:param second_dict: second dict to merge"""...defmerge_many(dicts:List[dict])->dict:"""Merge list of dicts.If more than one given dict defines the same key,then the one that is later in the argument sequence takes precedence.:param dicts: list of dicts:return: merged dict"""...defmerge_many_inplace(dicts:List[dict])->None:"""Merge list of dicts inplaceIf more than one given dict defines the same key,then the one that is later in the argument sequence takes precedence.:param dicts: list of dicts"""Installation# via pypipipinstalldict_merger# via gitpipinstallgit+https://github.com/TeaDove/dict_merger.git#@branch/tag# build locallygitclonehttps://github.com/TeaDove/dict_merger.git#@branch/tagcddict_merger
makeinstallPerformance testsdict_merger.static_merger - cython mergers with static typesdict_merger.dynamic_merger - cython mergers with dynamic typestests.pure_python - pure python implementation mergerstest_merge_inplace_random[dict_merger.static_merger] 101.64757675000146test_merge_inplace_random[dict_merger.dynamic_merger] 111.33557962499981test_merge_inplace_random[tests.pure_python] 346.21198354100125test_merge_static[dict_merger.static_merger] 4.421063124998909test_merge_static[dict_merger.dynamic_merger] 4.379016041999421test_merge_static[tests.pure_python] 4.7141847090024385test_merge_inplace_static[dict_merger.static_merger] 0.21805158300048788test_merge_inplace_static[dict_merger.dynamic_merger] 0.2745717500001774test_merge_inplace_static[tests.pure_python] 0.6025681659994007test_merge_many_static[dict_merger.static_merger] 4.533137833001092test_merge_many_static[dict_merger.dynamic_merger] 4.706059832999017test_merge_many_static[tests.pure_python] 5.675890833001176test_merge_many_inpace_static[dict_merger.static_merger] 0.42021320900312276test_merge_many_inpace_static[dict_merger.dynamic_merger] 0.572701542001596test_merge_many_inpace_static[tests.pure_python] 1.5192962910005008CreditsFor any questions, suggestions etc. writepeter.ibragimov@gmail.comor to telegram:@teadove
Package: dictmsgr
dictmsgrDict Messenger inspired by Robot Operation System, publish topic by setting item to a dict-likeContextobject. Callback subscription can be registered to be used in a single thread. The callback function should have signaturecallback(ctx, msg)and will be called whenContext.__setitem__()is fired. This dict is designed to function like a project-wide globals() that you can read&write. '/' is used to specify multi-level nested dict keys.pip install dictmsgr
Package: dictmysql
PyPI page:https://pypi.python.org/pypi/dictmysqlDocumentation:https://git.io/dictmysqlIntroductionDictMySQL is a MySQL query builder on the top ofPyMySQL. It allows convenient
database manipulation with Python dictionary.DictMySQL simplifies and unifies the input/output of MySQL queries, by
allowing passing values and conditions in dictionary into database. With
DictCursor, you can even have a dict-in, dict-out mysql connector.To install:pipinstalldictmysqlQuick example:fromdictmysqlimportDictMySQLdb=DictMySQL(db='occupation',host='127.0.0.1',user='root',passwd='')db.select(table='jobs',columns=['id','value'],where={'$OR':[{'value':{'$LIKE':'Artist%'}},{'id':10}]})# SELECT `id`, `value` FROM `jobs` WHERE (`value` LIKE "Artist%") OR (`id` = 10);With DictCursor:fromdictmysqlimportDictMySQL,cursorsdb=DictMySQL(db='occupation',host='127.0.0.1',user='root',passwd='',cursorclass=cursors.DictCursor)db.select(table='jobs',columns=['id','value'],limit=2)# returns [{u'id': 1, u'value': u'Artist'}, {u'id': 2, u'value': u'Engineer'}]Future WorksFull support of CRUDBetter documentsLicenseDictMySQL uses the MIT license, seeLICENSEfile for the details.
Package: dictns
simple python class that merges dictionary and object APIsThose Namespace objects work in a similar way as javascript objects.
intended to help deadling with deep json objects, and save you a lot of [‘’] in your codeusagefromdictnsimportNamespacen=Namespace(dict(a=1,b=3,c=dict(d=4)))assert(n['a']==n.a)assert(n['c']['d']==n.c.d)you can wrap dicts and lists inside Namespacen=Namespace([dict(a=1,b=3,c=[dict(d=4)])])assert(n[0]['a']==n[0].a)assert(n[0]['c'][0]['d']==n[0].c[0].d)you can also wrap dict subclasses like OrderedDict, but the resulting Namespace
does not inherit original object characteristics (i.e. order in OrderedDict)see unit tests for more usage examplesChangeLog:1.0: Initial version1.1: Added Namespace comparaison tools1.2: Namespace now support dict and list subclasses as input1.3:Fix for compatibility with getattr() built-in method. When an invalid key is requested, it
now raises an AttributeError instead of a KeyError.Allow initialization without arg: Namespace() is equivalent to Namespace({}).1.4: Allow Namespace objects to be weak referenced1.5:Fix tests for 3.5 and pypyReadme cleanupsDevelopingLaunch unit tests:python test/test_namespace.py
Package: dicto
dictoA dict-like object that enables access of its elements as regular fields. Dicto's main feature is delivering an elegant experience while using configuration files/objects.ExampleYou can create a Dicto from anydict:importdictoparams=dicto.Dict({"learning_rate":0.001,"batch_size":32})optimizer=Adam(params.learning_rate)Dicto parses through arbitrary nested structures ofdicts,list,tuple, andset:importdictoparams=dicto.Dict({"points":[{"x":1,"y":2},{"x":3,"y":4}]})print(params.points[0].x)# 1dictocan loadjson,yaml, andxmlformats directly, for example, given thisYAMLfile# params.ymllearning_rate:0.001batch_size:32you can load it like this:importdictoparams=dicto.load("params.yml")optimizer=Adam(params.learning_rate)InstallationpipinstalldictoLicenseMIT License
Package: dictoat
DictoatDictoat is a Python utility designed to simplify accessing data stored in dictionaries. It converts dictionaries into Python objects, allowing for more intuitive access to data via attributes instead of dictionary keys. This is ideal for projects where readability and ease of access to complex data structures are essential.InstallationYou can easily installDictoatusing pip:pipinstalldictoatUsageTo use Dictoat, simply import theDictoatclass in your Python project and pass a dictionary as an argument. For example:fromdictoatimportDictoat# Example of using Dictoatapple_dict={"color":"red","dimentions":{"weigh":185,"radius":5,"units":["g","cm"]}}apple=Dictoat(apple_dict)# Accessing the dataprint(apple.color_)print(apple.dimentions_.radius_)print(apple.dimentions_.units_)The output would show:red
5
['g', 'cm']Or a more complete example:fromdictoatimportDictoatpokedex_dict={"total_pokemons":2,"region":"Kanto","Pokemons":{"Pikachu":{"type":"Electric","abilities":["Static","Lightning Rod"],"stats":{"hp":35,"attack":55,"defense":40}},"Squirtle":{"type":"Water","abilities":["Torrent","Rain Dish"],"stats":{"hp":44,"attack":48,"defense":65},"evolutions":["Wartortle","Blastoise"]}}}pokedex=Dictoat(pokedex_dict)# Accessing the dataprint("Total Pokémon in Pokedex:",pokedex.total_pokemons_)print("Pokedex Region:",pokedex.region_)print("Pikachu Type:",pokedex.Pokemons_.Pikachu_.type_)print("Pikachu Abilities:",pokedex.Pokemons_.Pikachu_.abilities_)print("Pikachu HP:",pokedex.Pokemons_.Pikachu_.stats_.hp_)print("Squirtle Type:",pokedex.Pokemons_.Squirtle_.type_)print("Squirtle Abilities:",pokedex.Pokemons_.Squirtle_.abilities_)print("Squirtle Defense:",pokedex.Pokemons_.Squirtle_.stats_.defense_)print("Squirtle Evolutions:",pokedex.Pokemons_.Squirtle_.evolutions_)With its output being:Total Pokémon in Pokedex: 2
Pokedex Region: Kanto

Pikachu Type: Electric
Pikachu Abilities: ['Static', 'Lightning Rod']
Pikachu HP: 35

Squirtle Type: Water
Squirtle Abilities: ['Torrent', 'Rain Dish']
Squirtle Defense: 65
Squirtle Evolutions: ['Wartortle', 'Blastoise']FeaturesSimple Conversion: Converts any dictionary into an object for easier access.Deep Nesting Support: Supports nested dictionaries, creating sub-objects for each level.ContributionsContributions are welcome! If you have improvements or fixes, please send a pull request or open an issue in the GitHub repository.LicenseThis project is licensed under the MIT License. See theLICENSEfile for more details.ContactNico Spok -nicospok@hotmail.comGitHub: niCodeLine
Package: dict-objectify
Dict Objectify (DO) allows specification of python classes hierarchy that are
backed by dictionaries. Specification is done similar to ORM frameworks,
by declaratively specifying dictionary keys as fields,
Every field is defined as either nested (DO) class for nested dictionaries
or one of the provided type classes for values of the
type: int, float, text, bool, array, datetime or enum.Mapping between dictionaries and these objects works both ways.This allows easy parsing of hierarchical documents into python object hierarchy,
doing pre processing on dict values, doing any kind of processing on
that hierarchy and then transforming root objects back into dictionaries
for eventual dumping into same document formats.
Package: dictok
DicTokA dictionary-based tokenizer.
It tokenizes a text based on known tokens.Installationpip install dictokUsageCreate your dic-file with a list of tokens e.g.tokens.dic:super
man
note
book
store
...Importdictokand pass it the dictionary file as main parameter:>>> import dictok
>>> dt = dictok.DicTok('tokens.dic')You are ready to use it:>>> sent = "Superman bought a notebook in the bookstore."
>>> dt.tokenize(sent)
['Super', 'man', 'bought', 'a', 'note', 'book', 'in', 'the', 'book', 'store', '.']OptionsYou can also ignore single characters or unknown tokens:>>> dt.tokenize(sent, include_unknown = False, include_single_chars = False)
['Super', 'man', 'note', 'book', 'book', 'store']If you want to rewrite words or, for example, recognize and correct words with typing errors,
you can do so by specifying them as pair in the dictionary:super
man
bought,buy
note
book
buok,book
store
stohre,store
...>>> dt = dictok.DicTok('tokens.dic')
>>> sent = "Superman bought a notebuok in the bookstohre."
>>> dt.tokenize(sent, include_unknown = False, include_single_chars = False)
['Super', 'man', 'buy', 'note', 'book', 'book', 'store']
Package: dictol
DICTOL - A Discriminative dictionary Learning Toolbox for Classification (Python 2.7 version).This repo is a part of ourLRSDL project.Related publications:Tiep H. Vu, Vishal Monga. "Learning a low-rank shared dictionary for object classification."International Conference on Image Processing (ICIP)2016.[paper].Tiep H. Vu, Vishal Monga. "Fast Low-rank Shared Dictionary Learning for Image Classification."IEEE Transactions on Image Processing26.11(2017):5160-5175[paper].Author:Tiep VuThis repository contains the following methods: SRC, ODL, DLSI, FDDL, COPAR, LRSDLIf you experience any bugs, please let me know via theIssuestab. I'd really appreciate and fix the error ASAP. Thank you.For more information, please see its correspondingMATLAB version.Packages requirednumpyscipyInstallationpip install dictolDemoimport dictol
dictol.demo()Contact informationTiep Vu: 
    + vuhuutiep@gmail.com 
    + http://www.personal.psu.edu/thv102/
Package: dictondisk
dictondiskIt's a thing that implements a dictionary, but in a temporary directory.Why?I had a machine with not a lot of RAM and a script that was RAM-hungry.
Instead of optimizing the script i didthismontrostity.Should you use it?Probably not. It's slow. I'm almost certain there are many security flaws in this approach.How to use dictondisk?fromdictondiskimportDictOnDisksome_dict=DictOnDisk()some_dict[1]="One"some_dict[2]="Two"some_dict[3]="Three"delsome_dict[1]forkey,valueinsome_dict.items():print(key,value)Comparison to the vanilla dictActiondict()DictOnDisk()Preserve insertion order✔️❌len(d)✔️✔️d[key]✔️✔️d[key] = value✔️✔️del d[key]✔️✔️key in d✔️✔️key not in d✔️✔️iter(d)✔️✔️d.clear()✔️✔️d.copy()✔️✔️d.fromkeys()✔️✔️d.get(key[, default])✔️✔️d.items()✔️✔️d.keys()✔️✔️d.pop(key[, default])✔️✔️d.popitem()✔️✔️d.setdefault(key[, default])✔️✔️d.update([other])✔️✔️d.values()✔️✔️bool(d)✔️✔️d1 == d2✔️✔️d1 != d2✔️✔️
Package: dictones
DescriptionLike dict, but a little bit betterinstallpip install dictonesimportfromdictonesimportDictOnesUsage1. Added constructorfilled_dict=DictOnes('first_key, second_key','to first key','to second key')print(filled_dict.first_key)print(filled_dict.second_key)Output'to first key''to second_key'2. Constructor without fillingfilled_dict=DictOnes('first_key, second_key')print(filled_dict.first_key)print(filled_dict.second_key)print(filled_dict.key)OutputNoneNone...raise KeyError(attrname)KeyError: 'key'3. Deletingfilled_dict=DictOnes('first_key, second_key')print(filled_dict.first_key)print(filled_dict.second_key)print('second_key'infilled_dict)delfilled_dict.second_keyprint('second_key'infilled_dict)OutputNoneNoneTrueFalseOtherwise it is the same dict
Package: dictoo
DICTionary OperationsIs a library that makes applying functions to and performing operations on nested dicts easy.This repository attempts to unify numerous utilities in one package.Python >=3.7 is required as retained dict order is wanted.Python library that inspired this project:TODO: linkshttps://github.com/glowdigitalmedia/dict-utils/tree/master/dict_utilshttps://github.com/katsudonik/dict_utilhttps://github.com/gmr/flatdict/blob/master/flatdict.pyhttps://github.com/bunbun/nested-dicthttps://github.com/jacobflanagan/nesteddictionaryhttps://github.com/ducdetronquito/scalplhttps://github.com/mewwts/addicthttps://github.com/zphang/sndicthttps://github.com/nickstanisha/nesteddicthttps://github.com/bunbun/nested-dictFeaturesScalpl seems to be the most polished library. Dicty differs with some slight changes in the api
and additional set of functionality for operating on json like data structure:apply an operation to multiple dictoos with same shapesetting the type for the dictoos valuesSetuppip install dictooUsageimport dictoo.Dicty as D

# you can configure dictoo to fit your needs
# dictoo only imports and uses what is enabled
dictoo.CONFIG.update({
	'delimiter': '.'
})

# you can create dictoo dicts from many things
d = D(dict(a=1, b=[3, dict(c=4)]))
d = D.from_file('dict.yaml')
d = D.from_file('dict.json')
d = D("{a:1, b[0]:3, b[1].c=4}")  //not sure whether this is a good idea

assert d.b[1].c == d['b.[1].c']

d.update(dict(b=[5, dict(c=9)]))

d.flat()

dictoo.apply(lambda x, y: x + y, d1, d2, kwargs)

dictoo.reduce(fn, [d1, d2, d3], kwargs)

dictoo.remap({'old_key_name': 'new_key_name'})

d = D([{'a': 1, 'b': 2}, {'a':4, 'b':5})
isinstance(d, list) == True
isinstance(d, dict) == False
assert d != [D({'a': 1, 'b': 2}), D({'a':4, 'b':5})]  # try not to leave lists of Ds as you would also not do with numpy arrays
assert d == D([D({'a': 1, 'b': 2}), D({'a':4, 'b':5})])
d[:, 'a'] = 8  # D([{'a': 8, 'b': 2}, {'a':8, 'b':5}])  # this is hard to get used to, maybe be more strict here such that the code is more readable. Should be configurable
d[:1, 'a'] = 8  # only modifies a slice

d.batch()['a'][:] = 8

d: Dict[str, Union[np.ndarray, dict]] = D(dict(...), dtype=np.ndarray)

d.batch()  # D({'a': [1, 4], 'b': [2, 5]}), batch goes from lowest level to top level and unbatch inreverse

# more features:
# cli for json and yaml files
# regex keys
Package: dictools
dictoolsdictools- a set of recursive functions for manipulating Python dictionariesContents:Installation|Requirements|Versioning|Authors|LicenseGetting StartedInstallationFrom pippip install --upgrade dictoolsManual installgit clone https://github.com/evbg/dictools.git
cd dictools
python setup.py installInstalling directly from therepositoryon GitHub.compip install git+https://github.com/evbg/dictools.gitRequirementsdictools has no dependencies except Python itselfVersioningWe useSemVerfor versioning.AuthorsEvgeny V. Bogodukhov-Initial work-evbgLicenseThis project is licensed under the MIT License - see theLICENSEfile for details
Package: dictop
dictopDICT-OPERATION allow you select data value from a dict-instance with dot separated path, and update.Installpip install dictopTest Passed On Python2.73.23.33.43.53.63.73.83.93.103.11Usagefrom dictop import update
    from dictop import select

    data = {}
    update(data, "a.b.c", 2)
    assert select(data, "a.b.c") == 2Core Functionsselectselect(target, path, default=None, slient=True)updateupdate(target, path, value)Unit Tests# tests.py

import unittest
import dictop

class DictopTest(unittest.TestCase):


    def test01(self):
        data = {
            "a": {
                "b": "value",
            }
        }
        assert dictop.select(data, "a.b") == "value"
        assert dictop.select(data, "a.c") is None
    
    def test02(self):
        data = {
            "a": [{
                "b": "value",
            }]
        }
        assert dictop.select(data, "a.0.b") == "value"
        assert dictop.select(data, "a.1.b") is None

    def test03(self):
        data = [1,2,3]
        assert dictop.select(data, "0") == 1
        assert dictop.select(data, "4") is None

    def test04(self):
        data = {}
        dictop.update(data, "a.b.c", "value")
        dictop.select(data, "a.b.c") == "value"
    
    def test05(self):
        data = []
        dictop.update(data, "1.a.b", "value")
        assert data[1]["a"]["b"] == "value"Releases0.1.0 2018/03/20First release.0.1.1 2018/03/200.1.2 2018/04/020.1.3 2018/04/180.1.4 2019/04/12Update.0.2.1 2022/01/08Fix license file missing problem.0.2.2 2023/09/08Add gitlab-ci and tested on all python versions.