[Python] I made a utility that can access dict type like a path

Postscript (2017.02.27)

I didn't know at the time of writing, but if you just want to access the dict by attribute, attrdict is Don Pisha.

It can be used as follows (quoted from the official document)

from attrdict import AttrDict
a = AttrDict({'foo': 'bar'})
a.foo

'bar'

a['foo'] 'bar'


# Overview and motivation
 When handling the Web-API response that returns json with python.
 Generally, the hierarchy is deep, and it is troublesome to refer to it while checking the value for each hierarchy.
 So, I thought it would be useful to have a _parse_ function that gives the following execution result.

```python
some_dict = {
	"path":{
		"to":{
			"target": 
				"key": 1 }}}

# expected return: 1
parse(some_dict, "/path/to/target/key")

# expected return: None
parse(some_dict, "/fake/key")

It feels like a kind of query parser in terms of operation.

Consideration

――If you use recursion, you can write it quickly. ――I thought it would be nice if you could refer to it like a path format, but the point is to write a split that supports dictionary type. --If the delimiter is fixed to "/", it will break if the key is "a / b". --If so, it is OK if the delimiter can be specified in kwarg format.

Implementation

Minimal implementation.

d = {
	'a': 1,
	'b': [1, 2, 3],
	'c': {
		'ca': 1,	
		'cb': [2, 3, 4] }}

d2 = {
	'a': 1,
	'a/x': 2,
	'b': {
		'ba': 100 }}

def dparse(dic, p, sep="/", default=None):
	lis = p.split(sep)
	def _(dic, lis, sep, default):
		if len(lis) == 0:
			return default
		if len(lis) == 1:
			return dic.get(lis[0], default)
		else:
			return _(dic.get(lis[0], {}), lis[1:], sep, default)
	return _(dic, lis, sep=sep, default=None)

if __name__=="__main__":
	print dparse(d, "a") # 1
	print dparse(d, "c/cb") # [2, 3, 4]
	print dparse(d2, "a/x", sep=":") # 2
	print dparse(d2, "b:ba", sep=":") # 100

Name dparse appropriately with an image that makes dict parse.

Postscript

There should be various loopholes, so I'm waiting for Tsukkomi. The quick idea is that this function will break if it contains "None as value". It is a logical error source because it is not possible to distinguish between "non-existent" and "None as a value". The essence is the same because the default argument is specified other than None.

It may be better to raise the "non-existent" case obediently.

To those who read this

I think that a utility of this level is probably a reinvention of the wheel, so I would like to know if there is an existing good means to achieve this purpose.

The code or design is awkward, write this! We welcome your suggestions.

I chose dparse for the function name because I couldn't think of an appropriate name, but I couldn't express the name as a body, so if I had a good idea.

Recommended Posts

[Python] I made a utility that can access dict type like a path
I made a package that can compare morphological analyzers with Python
I made a shuffle that can be reset (reverted) with Python
[python] I made a class that can write a file tree quickly
I made a module PyNanaco that can charge nanaco credit with python
I made a Docker image that can call FBX SDK Python from Node.js
I made a familiar function that can be used in statistics with Python
I made a VM that runs OpenCV for Python
I made a python text
I made a puzzle game (like) with Tkinter in Python
I made a plug-in that can "Daruma-san fell" with Minecraft
I made a fortune with Python.
I made a daemon with Python
[Python] I made a Line bot that randomly asks English words.
[Python3] I made a decorator that declares undefined functions and methods.
[Python] I made my own library that can be imported dynamically
I made a library that adds docstring to a Python stub file.
I made a payroll program in Python!
I made a character counter with Python
I made a conversation partner like Siri
I made a Hex map with Python
After studying Python3, I made a Slackbot
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
I created a template for a Python project that can be used universally
I made a web application in Python that converts Markdown to HTML
I made a Discord bot in Python that translates when it reacts
I made a simple timer that can be started from the terminal
I made a tool that makes decompression a little easier with CLI (Python3)
[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
[Python] I made a function that can also use regular expressions that replace character strings all at once.
I made a python dictionary file for Neocomplete
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
A memo that I wrote a quicksort in Python
I tried to create a class that can easily serialize Json in Python
I made a Line Bot that uses Python to retrieve unread Gmail emails!
I want to create a priority queue that can be updated in Python (2.7)
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
In Python, I made a LINE Bot that sends pollen information from location information.
A story that I was addicted to when I made SFTP communication with python
I made a Caesar cryptographic program in Python.
I made a bin picking game with Python
I made a Mattermost bot with Python (+ Flask)
I made a Python Qiita API wrapper "qiipy"
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
I made my own Django Middleware so that I can access request information from anywhere
I made a Twitter BOT with GAE (python) (with a reference)
Python that I would like to recommend to programming beginners
I made a prime number generation program in Python
I made a login / logout process using Python Bottle.
I made a Christmas tree lighting game with Python
I made a Python module to translate comment outs
I made a Python3 environment on Ubuntu with direnv.
From a book that programmers can learn ... (Python): Pointer
I made a LINE BOT with Python and Heroku
[Python] I made a classifier for irises [Machine learning]
A memo that I touched the Datastore with python