Python switch statement with aliases - python

How to write an efficient "switch" statement that can return same thing for different input?
Simple switch in Python can be implemented using dictionary like this:
def switch(s):
case = {'phone': '123 456 789', 'website': 'www.example.com'}
return case[s]
This one has constant access time, however I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values, i.e. without using
case = {'website': 'www.example.com, 'site': 'www.example.com}
What can be used, is:
def switch(s):
case = {('telephone', 'number', 'phone'): '123 456 789',
('website', 'site'): 'www.example.com'}
for key, value in case.items():
if s in key:
return value
But this approach has worse than linear access time.
It can be made constant, by using
def switch(s):
case = ['123 456 789', 'www.example.com']
aliases = {'telephone': 0, 'number': 0, 'phone': 0,
'website': 1, 'site': 1}
return case[aliases[s]]
but then I'm sort-of duplicating values and in case I decide to remove any answer, I have to edit aliases' and/or case's return values (if I no longer want to return '123 456 789' I have to delete it from case and modify aliases so that aliases['website'] and aliases['site'] return 0 OR leave dummy value in case's 1st cell OR make case a dictionary)
Is there a better way to write such statements?

You can use the linked hashmaps approach:
def switch(s):
alias = {'telephone': 1, 'number': 1, 'phone': 1,
'website': 2, 'site': 2}
case = {1: '123 456 789', 2: 'www.example.com'}
return case[alias[s]]
That way you are keeping the O(1) lookup time.
Of course, for real data, you'll want to automate the construction of alias and case maps, but that should be rather straightforward.
Updates/deletes should also be rather simple, since they come down to simple dict update/delete.
Also, to make insertion of new values easier, you can use UUID4 (or some other random value) instead of numbers.

I would simply use an aliases dictionary without identity aliases besides your original case dictionary and check for potential aliases using get:
def switch(s):
case = {'phone': '123 456 789', 'website': 'www.example.com'}
aliases = {'telephone': 'phone', 'number': 'phone', 'site': 'website'}
return case[aliases.get(s, s)] # check if it's an alias or use the input as-is
That way you don't need to duplicate the values (not in case and not in alias).

In your question you say:
I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values
I think your concern about duplicated values is misplaced and you shouldn't reject that approach. Adding an extra dictionary entry with the same string value should not be a problem, and it's the natural way to solve your issue. Don't complicate your code with an extra indirection layer if you don't need to.
I'm assuming your concern with that approach is that it could increase your memory usage, since identical values are stored several times in the dictionary. But most of the time, you won't have multiple separate identical strings, rather, you'll have multiple references to the same string object. Since strings are immutable, Python may substitute in references to preexisting objects when it would appear it should be creating another independent string with the same contents.
You can test this for yourself. Try creating a dictionary with several identical string literals as values, then test the id of each one:
d = {"a": "foo", "b": "foo", "c": "foo"}
for val in d.values():
print(id(val))
On my system this tells me the ids are all the same. I think that multiple identical string literals that are compiled at the same time will always be turned into multiple references to a single string object. In some situations, thanks to string "interning", all strings with certain contents (generally things that look like they could be identifiers) will be shared everywhere in the program. But you probably don't need to care too much about the details. The important thing to realize is that the duplicated strings probably won't use an excessive amount of memory most of the time.
I can't think of any other reason to object to adding all the aliases to a single dictionary. That's the natural solution, so I'd just do it. If memory usage turns out to be an issue later, you might revisit the dictionary to double check that it's being populated with repeated references, not duplicate objects, but I doubt it will matter on the scale of any serious program.
Having code that is easy to use and understand is much more important.
As you've commented that your main concern is not repeating yourself, you might want to set up the dictionary using code to transform another slightly less redundant data structure, rather than doing it directly as a literal.
For instance, the following code uses a dictionary comprehension to turn a list that pairs up sublists of aliases with their values into an easily searchable dictionary:
_data = [ # contains (alias_list, value) 2-tuples
(['telephone', 'number', 'phone'], '123 456 789'),
(['website', 'site'], 'www.example.com'),
]
case = {alias: value for aliases, value in _data for alias in aliases}
You probably want to put this code somewhere where it will only run once (e.g. at the top level, or in a class or instance variable somewhere), rather than having the dictionary comprehension run every time your switch function is called. Because the dictionary is mutable, Python won't assume it can use the same dict object for each call (even though it always has the same value).

Related

Fast String "Startswith" Matching for Dict like object

I currently have some code which needs to be very performant, where I am essentially doing a string dictionary key lookup:
class Foo:
def __init__(self):
self.fast_lookup = {"a": 1, "b": 2}
def bar(self, s):
return self.fast_lookup[s]
self.fast_lookup has O(1) lookup time, and there is no try/if etc code that would slow down the lookup
Is there anyway to retain this speed while doing a "startswith" lookup instead? With the code above calling bar on s="az" would result in a key error, if it were changed to a "startswith" implementation then it would return 1.
NB: I am well aware how I could do this with a regex/startswith statement, I am looking for performance specifically for startswith dict lookup
An efficient way to do this would be to use the pyahocorasick module to construct a trie with the possible keys to match, then use the longest_prefix method to determine how much of a given string matches. If no "key" matched, it returns 0, otherwise it will say how much of the string passed exists in the automata.
After installing pyahocorasick, it would look something like:
import ahocorasick
class Foo:
def __init__(self):
self.fast_lookup = ahocorasick.Automaton()
for k, v in {"a": 1, "b": 2}.items():
self.fast_lookup.add_word(k, v)
def bar(self, s):
index = self.fast_lookup.longest_prefix(s)
if not index: # No prefix match at all
raise KeyError(s)
return self.fast_lookup.get(s[:index])
If it turns out the longest prefix doesn't actually map to a value (say, 'cat' is mapped, but you're looking up 'cab', and no other entry actually maps 'ca' or 'cab'), this will die with a KeyError. Tweak as needed to achieve precise behavior desired (you might need to use longest_prefix as a starting point and try to .get() for all substrings of that length or less until you get a hit for instance).
Note that this isn't the primary purpose of Aho-Corasick (it's an efficient way to search for many fixed strings in one or more long strings in a single pass), but tries as a whole are an efficient way to deal with prefix search of this form, and Aho-Corasick is implemented in terms of tries and provides most of the useful features of tries to make it more broadly useful (as in this case).
I dont fully understand the question, but what I would do is try and think of ways to reduce the work the lookup even has to do. If you know the basic searches the startswith is going to do, you can just add those as keys to the dictionary and values that point to the same object. Your dict will get pretty big pretty fast, however it will greatly reduce the lookup i believe. So maybe for a more dynamic method you can add dict keys for the first groups of letters up to three for each entry.
Without activly storing the references for each search, your code will always need to get each dict objects value until it gets one that matches. You cannot reduce that.

Pandas dataframe from dict, why?

I can create a pandas dataframe from dict as follows:
d = {'Key':['abc','def','xyz'], 'Value':[1,2,3]}
df = pd.DataFrame(d)
df.set_index('Key', inplace=True)
And also by first creating a series like this:
d = {'abc': 1, 'def': 2, 'xyz': 3}
a = pd.Series(d, name='Value')
df = pd.DataFrame(a)
But not directly like this:
d = {'abc': 1, 'def': 2, 'xyz': 3}
df = pd.DataFrame(d)
I'm aware of the from_dict method, and this also gives the desired result:
d = {'abc': 1, 'def': 2, 'xyz': 3}
pd.DataFrame.from_dict(d, orient='index')
but I don't see why:
(1) a separate method is needed to create a dataframe from dict when creating from series or list works without issue;
(2) how/why creating a dataframe from dict/list of lists works, but not creating from dict directly.
Have found several SE answers that offer solutions, but looking for the 'why' as this behavior seems inconsistent. Can anyone shed some light on what I may be missing here.
There's actually a lot happening here, so let's break it down.
The Problem
There are soooo many different ways to create a DataFrame (from a list of records, dict, csv, ndarray, etc ...) that even for python veterans it can take a long time to understand them all. Hell, within each of those ways, there are EVEN MORE ways to build a DataFrame by tweaking some parameters and whatnot.
For example, for dictionaries (where the values are equal length lists), here are two ways pandas can handle them:
Case 1:
You treat each key-value pair as a column title and it's values at each row respectively. In this case, the rows don't have names, and so by default you might just name them by their row index.
Case 2:
You treat each key-value pair as the row's name and it's values at each column respectively. In this case, the columns don't have names, and so by default you might just name them by their index.
The Solution
Python's is a weakly typed language (aka variables don't declare a type and functions don't declare a return). As a result, it doesn't have function overloading. So, you basically have two philosophies when you want to create a object class that can have multiple ways of being constructed:
Create only one constructor that checks the input and handles it accordingly, covering all possible options. This can get very bloated and complicated when certain inputs have their own options/parameters and when there's simply just too much variety.
Separate each option into #classmethod's to handle each specific individual way of constructing the object.
The second is generally better, as it really enforces seperation of concerns as a SE design principle, however the user will need to know all the different #classmethod constructor calls as a result. Although, in my opinion, if you're object class is complicated enough to have many different construction options, the user should be aware of that anyways.
The Panda's Way
Pandas adopts a sorta mix between the two solutions. It'll use the default behaviour for each input type, and it you wanna get any extra functionality you'll need to use the respective #classmethod constructor.
For example, for dicts, by default, if you pass a dict into the DataFrame constructor, it will handle it as Case 1. If you want to do the second case, you'll need to use DataFrame.from_dict and pass in orient='index' (without orient='index', it would would use default behaviour described base Case 1).
In my opinion, I'm not a fan of this kind of implementation. Personally, it's more confusing than helpful. Honestly, a lot of pandas is designed like that. There's a reason why pandas is the topic of every other python tagged question on stackoverflow.

How to search/traverse for specific key in dict for updating value in python?

Using python 2.x, suppose I have the following:
target = {'field':'occupation', 'value':'Sanitation Specialist'}
thedict = {'name:':'Wilson','hobbies':['Sports', 'Basketball','Volleyball'], 'job':{
'occupation': 'Janitor',
'years_worked': 5,
'locations': {
'loc_name': 'CompanyA',
'loc_alias': 'The Finest Company',
},
'married': 'Yes'
'children': 5
}};
How to create a function such that I can replace the value in the nested field CnestedA with value without hardcoding the fact that the CnestedA field is actually nested in fieldC (i.e. thedict['job']['occupation']? The function should take a "target" object like above, and a thedict to be updated. Note that if the 'target' object stayed the same, but in the dict, occupation happened to be an immediate key in thedict, (i.e. thedict['occupation']), the function would still work. If it doesnt find the field, then nothing happens to thedict.
You could do this with a recursive search algorithm, but it'd be inefficient. Instead, it'd be a better idea to either reorganize your data or create an auxiliary data structure that records where each field is.
To reorganize your data for efficient lookup, you'd de-nest your dict, moving all keys to the top-level dict. If you need information previously encoded in the path to the key, put that into the value. Then, to perform an update, you'd use
denested_dict[key] = value
or
denested_dict[key].data = value
if you created some sort of value object with a data field for what used to be the value and a path field to record the old path.
If it's inconvenient to reorganize your data, you can instead create a dict that maps each key to the dict that has that key. Then, to update an arbitrarily nested key, you'd use the new dict to look up the dict to update and update that.
index_dict[key][key] = value

Python: in-memory object database which supports indexing?

I'm doing some data munging which would be quite a bit simpler if I could stick a bunch of dictionaries in an in-memory database, then run simply queries against it.
For example, something like:
people = db([
{"name": "Joe", "age": 16},
{"name": "Jane", "favourite_color": "red"},
])
over_16 = db.filter(age__gt=16)
with_favorite_colors = db.filter(favorite_color__exists=True)
There are three confounding factors, though:
Some of the values will be Python objects, and serializing them is out of the question (too slow, breaks identity). Of course, I could work around this (eg, by storing all the items in a big list, then serializing their indexes in that list… But that could take a fair bit of fiddling).
There will be thousands of data, and I will be running lookup-heavy operations (like graph traversals) against them, so it must be possible to perform efficient (ie, indexed) queries.
As in the example, the data is unstructured, so systems which require me to predefine a schema would be tricky.
So, does such a thing exist? Or will I need to kludge something together?
What about using an in-memory SQLite database via the sqlite3 standard library module, using the special value :memory: for the connection? If you don't want to write your on SQL statements, you can always use an ORM, like SQLAlchemy, to access an in-memory SQLite database.
EDIT: I noticed you stated that the values may be Python objects, and also that you require avoiding serialization. Requiring arbitrary Python objects be stored in a database also necessitates serialization.
Can I propose a practical solution if you must keep those two requirements? Why not just use Python dictionaries as indices into your collection of Python dictionaries? It sounds like you will have idiosyncratic needs for building each of your indices; figure out what values you're going to query on, then write a function to generate and index for each. The possible values for one key in your list of dicts will be the keys for an index; the values of the index will be a list of dictionaries. Query the index by giving the value you're looking for as the key.
import collections
import itertools
def make_indices(dicts):
color_index = collections.defaultdict(list)
age_index = collections.defaultdict(list)
for d in dicts:
if 'favorite_color' in d:
color_index[d['favorite_color']].append(d)
if 'age' in d:
age_index[d['age']].append(d)
return color_index, age_index
def make_data_dicts():
...
data_dicts = make_data_dicts()
color_index, age_index = make_indices(data_dicts)
# Query for those with a favorite color is simply values
with_color_dicts = list(
itertools.chain.from_iterable(color_index.values()))
# Query for people over 16
over_16 = list(
itertools.chain.from_iterable(
v for k, v in age_index.items() if age > 16)
)
If the in memory database solution ends up being too much work, here is a method for filtering it yourself that you may find useful.
The get_filter function takes in arguments to define how you want to filter a dictionary, and returns a function that can be passed into the built in filter function to filter a list of dictionaries.
import operator
def get_filter(key, op=None, comp=None, inverse=False):
# This will invert the boolean returned by the function 'op' if 'inverse == True'
result = lambda x: not x if inverse else x
if op is None:
# Without any function, just see if the key is in the dictionary
return lambda d: result(key in d)
if comp is None:
# If 'comp' is None, assume the function takes one argument
return lambda d: result(op(d[key])) if key in d else False
# Use 'comp' as the second argument to the function provided
return lambda d: result(op(d[key], comp)) if key in d else False
people = [{'age': 16, 'name': 'Joe'}, {'name': 'Jane', 'favourite_color': 'red'}]
print filter(get_filter("age", operator.gt, 15), people)
# [{'age': 16, 'name': 'Joe'}]
print filter(get_filter("name", operator.eq, "Jane"), people)
# [{'name': 'Jane', 'favourite_color': 'red'}]
print filter(get_filter("favourite_color", inverse=True), people)
# [{'age': 16, 'name': 'Joe'}]
This is pretty easily extensible to more complex filtering, for example to filter based on whether or not a value is matched by a regex:
p = re.compile("[aeiou]{2}") # matches two lowercase vowels in a row
print filter(get_filter("name", p.search), people)
# [{'age': 16, 'name': 'Joe'}]
The only solution I know is a package I stumbled across a few years ago on PyPI, PyDbLite. It's okay, but there are few issues:
It still wants to serialize everything to disk, as a pickle file. But that was simple enough for me to rip out. (It's also unnecessary. If the objects inserted are serializable, so is the collection as a whole.)
The basic record type is a dictionary, into which it inserts its own metadata, two ints under keys __id__ and __version__.
The indexing is very simple, based only on value of the record dictionary. If you want something more complicated, like based on a the attribute of a object in the record, you'll have to code it yourself. (Something I've meant to do myself, but never got around to.)
The author does seem to be working on it occasionally. There's some new features from when I used it, including some nice syntax for complex queries.
Assuming you rip out the pickling (and I can tell you what I did), your example would be (untested code):
from PyDbLite import Base
db = Base()
db.create("name", "age", "favourite_color")
# You can insert records as either named parameters
# or in the order of the fields
db.insert(name="Joe", age=16, favourite_color=None)
db.insert("Jane", None, "red")
# These should return an object you can iterate over
# to get the matching records. These are unindexed queries.
#
# The first might throw because of the None in the second record
over_16 = db("age") > 16
with_favourite_colors = db("favourite_color") != None
# Or you can make an index for faster queries
db.create_index("favourite_color")
with_favourite_color_red = db._favourite_color["red"]
Hopefully it will be enough to get you started.
As far as "identity" anything that is hashable you should be able to compare, to keep track of object identity.
Zope Object Database (ZODB):
http://www.zodb.org/
PyTables works well:
http://www.pytables.org/moin
Also Metakit for Python works well:
http://equi4.com/metakit/python.html
supports columns, and sub-columns but not unstructured data
Research "Stream Processing", if your data sets are extremely large this may be useful:
http://www.trinhhaianh.com/stream.py/
Any in-memory database, that can be serialized (written to disk) is going to have your identity problem. I would suggest representing the data you want to store as native types (list, dict) instead of objects if at all possible.
Keep in mind NumPy was designed to perform complex operations on in-memory data structures, and could possibly be apart of your solution if you decide to roll your own.
I wrote a simple module called Jsonstore that solves (2) and (3). Here's how your example would go:
from jsonstore import EntryManager
from jsonstore.operators import GreaterThan, Exists
db = EntryManager(':memory:')
db.create(name='Joe', age=16)
db.create({'name': 'Jane', 'favourite_color': 'red'}) # alternative syntax
db.search({'age': GreaterThan(16)})
db.search(favourite_color=Exists()) # again, 2 different syntaxes
Not sure if it complies with all your requirements, but TinyDB (using in-memory storage) is also probably worth the try:
>>> from tinydb import TinyDB, Query
>>> from tinydb.storages import MemoryStorage
>>> db = TinyDB(storage=MemoryStorage)
>>> db.insert({'name': 'John', 'age': 22})
>>> User = Query()
>>> db.search(User.name == 'John')
[{'name': 'John', 'age': 22}]
Its simplicity and powerful query engine makes it a very interesting tool for some use cases. See http://tinydb.readthedocs.io/ for more details.
If you are willing to work around serializing, MongoDB could work for you. PyMongo provides an interface almost identical to what you describe. If you decide to serialize, the hit won't be as bad since Mongodb is memory mapped.
It should be possible to do what you are wanting to do with just isinstance(), hasattr(), getattr() and setattr().
However, things are going to get fairly complicated before you are done!
I suppose one could store all the objects in a big list, then run a query on each object, determining what it is and looking for a given attribute or value, then return the value and the object as a list of tuples. Then you could sort on your return values pretty easily. copy.deepcopy will be your best friend and your worst enemy.
Sounds like fun! Good luck!
I started developing one yesterday and it isn't published yet. It indexes your objects and allows you to run fast queries. All data is kept in RAM and I'm thinking about smart load and save methods. For testing purposes it is loading and saving through cPickle.
Let me know if you are still interested.
ducks is exactly what you are describing.
It builds indexes on Python objects
It does not serialize or persist anything
Missing attributes are handled correctly
It uses C libraries so it's very fast and RAM-efficient
pip install ducks
from ducks import Dex, ANY
objects = [
{"name": "Joe", "age": 16},
{"name": "Jane", "favourite_color": "red"},
]
# Build the index
dex = Dex(objects, ['name', 'age', 'favourite_color'])
# Look up by any combination of attributes
dex[{'age': {'>=': 16}}] # Returns Joe
# Match the special value ANY to find all objects with the attribute
dex[{'favourite_color': ANY}] # Returns Jane
This example uses dicts, but ducks works on any object type.

Access list of tuples

I have a list that contains several tuples, like:
[('a_key', 'a value'), ('another_key', 'another value')]
where the first tuple-values act as dictionary-keys.
I'm now searching for a python-like way to access the key/value-pairs, like:
"mylist.a_key" or "mylist['a_key']"
without iterating over the list. any ideas?
You can't do it without any iteration. You will either need iteration to convert it into a dict, at which point key access will become possible sans iteration, or you will need to iterate over it for each key access. Converting to a dict seems the better idea-- in the long run it is more efficient, but more importantly, it represents how you actually see this data structure-- as pairs of keys and values.
>>> x = [('a_key', 'a value'), ('another_key', 'another value')]
>>> y = dict(x)
>>> y['a_key']
'a value'
>>> y['another_key']
'another value'
If you're generating the list yourself, you might be able to create it as a dictionary at source (which allows for key, value pairs).
Otherwise, Van Gale's defaultdict is the way to go I would think.
Edit:
As mentioned in the comments, defaultdict is not required here unless you need to deal with corner cases like several values with the same key in your list. Still, if you can originally generate the "list" as a dictionary, you save yourself having to iterate back over it afterwards.

Categories

Resources