Python Array with String Indices - python

Is it possible to use strings as indices in an array in python?
For example:
myArray = []
myArray["john"] = "johns value"
myArray["jeff"] = "jeffs value"
print myArray["john"]

What you want is called an associative array. In python these are called dictionaries.
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"
Alternative way to create the above dict:
myDict = {"john": "johns value", "jeff": "jeffs value"}
Accessing values:
print(myDict["jeff"]) # => "jeffs value"
Getting the keys (in Python v2):
print(myDict.keys()) # => ["john", "jeff"]
In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).
print(myDict.keys()) # => dict_keys(['john', 'jeff'])
If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

Related

How do you create a class, or function in python that allows you to make a sequence type with specific characteristics

1) My goal is to create a sequence that is a list that contains ordered dictionaries. The only problem for me will be described below.
I want the list to represent a bunch of "points" which are for all intents and purposes just an ordered dictionary. However, I notice that when I use OrderedDict class, when I print the dictionary it comes up as OrderedDict([key value pair 1, key value pair 2, ... etc)] For me, I would rather it behave like an ordered dictionary, BUT not having those DOUBLE "messy/ugly" "end marks" which are the "[( )]". I don't mind if the points have ONE, and only one, type of "end marks". Also I would also like it if when I print this data type that stuff like OrderedDict() doesn't show up. However, I do not mind if it shows up in return values. Like you know how when you print a list it doesn't show up as list(index0, index1, ... etc) but instead it shows up as [index0, index1, ... etc]. That is what I mean. Inside the point, it would look like this
point = {'height': 1, 'weight': 3, 'age': 5, etc} <- It could be brackets or braces or parentheses. Just some type of "end mark", but I preferably would like it to be in {} and having key value pairs indicated by key: value and have them separated by commas.
what_i_am_looking_for = [point0, point1, point2, point3, ... etc]
In Python 3.6, the ordinary dict implementation was re-written and maintains key insertion order like OrderedDict, but was considered an implementation detail. Python 3.7 made this feature an official part of the language spec, so if you use Python 3.6+ just use dict instead of OrderedDict if you don't care about backward-compatibility with Python 3.5 or earlier.

What is the difference between using brackets "[]" and parentheses "()" for "fields" in django-rest-framework [duplicate]

What's the difference between () vs [] vs {} in Python?
They're collections? How can I tell when to use which?
() - tuple
A tuple is a sequence of items that can't be changed (immutable).
[] - list
A list is a sequence of items that can be changed (mutable).
{} - dictionary or set
A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1, {} can also represent a set of unique values (mutable).
() is a tuple: An immutable collection of values, usually (but not necessarily) of different types.
[] is a list: A mutable collection of values, usually (but not necessarily) of the same type.
{} is a dict: Use a dictionary for key value pairs.
For the difference between lists and tuples see here. See also:
Python Tuples are Not Just Constant Lists
() - tuple
[] - list
{} - dictionary
All Python tutorials should cover this. Here is a good place to start.
In addition to the tuple, list and dict given by the other answers, {} also denotes a set literal in python 2.7 and python 3.1. (This makes sense because set elements act like the keys of a dict).
To complete the other answers about {}:
If you see a = {"key1": 1, "key2": 2, "key3": 3} (keys and values), then it's a dict.
If you see a = {1, 2, 3} (values only), then it's a set.
If you see a = {} (empty), then it's a dict. An empty set is created with a = set().
Quoting the official doc:
5.4. Sets
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Any quick way in Python to create and access a hashtable?

I am trying to implement a LHS pattern match with a RHS action code in Python
How can I get a fast hashtable match.
Is this possible in Python?
I need to fast match features in terms of x,y,c where x and y are coordinates and c is the color at index(x,y) of a 2d array.
An hashmap is a dictionary in python.
There are several ways to create dictionaries, here's 2:
d = dict(k=v)
or
d = {k:v}
To get the value of a key:
k = d.get("k")
or
k = d[k]
To set the value of a key:
d[k] = "ok"
Notes:
In Python, dictionaries (or “dicts”, for short) are a central data
structure:
Dicts store an arbitrary number of objects, each identified by a
unique dictionary key. Dictionaries are often also called maps,
hashmaps, lookup tables, or associative arrays. They allow the
efficient lookup, insertion, and deletion of any object associated
with a given key.
Resources:
Dictionaries in Python
Dictionaries, Maps, and Hash Tables in Python
The native type dict is a hashmap, not a hashtable, therefore you can only values to a key.
You can however simulate a hashtable by using (x, y) tuples as keys:
d = {}
d[(1,0)] = True
d[(1,1)] = False
This works because the tuple type in Python is hashable, meaning that as long as the values that it wraps are hashable, it can convert the value to a key.
Otherwise, you could extend the dict type to provide additional methods, letting you access values in a Java- or C-style 2D array:
d[1][0] = True
d[1][1] = False

python dictionary float search within range

Suppose I have some kind of dictionary structure like this (or another data structure representing the same thing.
d = {
42.123231:'X',
42.1432423:'Y',
45.3213213:'Z',
..etc
}
I want to create a function like this:
f(n,d,e):
'''Return a list with the values in dictionary d corresponding to the float n
within (+/-) the float error term e'''
So if I called the function like this with the above dictionary:
f(42,d,2)
It would return
['X','Y']
However, while it is straightforward to write this function with a loop, I don't want to do something that goes through every value in the dictionary and checks it exhaustively, but I want it to take advantage of the indexed structure somehow (or a even a sorted list could be used) to make the search much faster.
Dictionary is a wrong data structure for this. Write a search tree.
Python dictionary is a hashmap implementation. Its keys can't be compared and traversed as in search tree. So you simply can't do it using python dictionary without actually checking all keys.
Dictionaries with numeric keys are usually sorted - by key values. But you may - to be on the safe side - rearrange it as OrderedDictionary - you do it once
from collections import OrderedDict
d_ordered = OrderedDict(sorted(d.items(), key =lambda i:i[0]))
Then filtering values is rather simple - and it will stop at the upper border
import itertools
values = [val for k, val in
itertools.takewhile(lambda (k,v): k<upper, d_ordered.iteritems())
if k > lower]
As I've already stated, ordering dictionary is not really necessary - but some will say that this assumption is based on the current implementation and may change in the future.

Why dictionary values aren't in the inserted order?

When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4.
But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand .
test1 = [4,1,2,3,6,5]
print test1
test2 = {"c":3,"a":1,"b":2,"d":4}
print test2
[4, 1, 2, 3, 6, 5]
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
How in the world did 'a' become the first element and 'c' , even if it alphabetically sorted the dictionary it should have been 1,2,3,4 or a,b,c,d not 1,3,2,4 . wT?F #!$!#$##!
So how do i print , get values from dictionary without changing the positions of the elements .?
Dictionaries in Python are unordered by definition. Use OrderedDict if you need the order in which values were inserted (it's available in Python 2.7 and 3.x).
dictionary sort order is undefined! Do not rely on it for anything. Look for a sorted dictionary if you really want a sorted dictionary, but usually you don't need one.
Examples:
python 2.7, it's built in to the collections module
Django has a SortedDict shipped with it
2.4-2.7 you can use the ordereddict module, you can pip install or easy_install it
Before you get so angry and frustrated, perhaps you should read about what a dictionary actually is and how it works:
http://docs.python.org/library/stdtypes.html#mapping-types-dict
Python dicts use a hash table as the underlying storage mechanism. That means that a hash key is generated from the key that you provide. There are no guarantees about ordering with these hash keys. The entries in a dictionary are fetched in sequential order of their location in the underlying hash table when you request values(), keys(), or items().
The advantage of using a hash table is that it is extremely fast. Unlike the map class from c++ which uses a red-black tree storage mechanism ( which is sorted by the raw keys ), a hash table doesn't constantly need to be restructured to keep it efficient. For more on hash tables, see:
http://en.wikipedia.org/wiki/Hash_table
Like the other posters have said, look up OrderedDict if you need to have a key-sorted dictionary.
Good Luck!
Clearly you know about lists. You can ask for the element at the ith index of a list. This is because lists are ordered.
>>> [1,2,3,4] == [1,4,3,2]
False
In this context, you can think of dictionaries, but where the index is the key. Therefore, two dictionaries are equal if the corresponding values of all keys in both dictionaries are the same (if one dictionary has keys that the other doesn't, then the two are not equal). Thus:
>>> {1:'a', 2:'b'} == {2:'b', 1:'a'}
True
Further Trivia
A dictionary does something called hashing on the keys of the dictionary so that when you ask for the value at a particular key (index), it can retrieve this value faster.
Hope this helps
Dictionaries are unsorted. This is well-documented. Do not rely on the ordering of dictionaries.
If you want to see the entries in order. something like:
test2 = {"c":3,"a":1,"b":2,"d":4}
ks = test2.keys()
ks.sort()
for key in ks:
print key + ':' + str(test2[key])
(cut,paste, season to taste)

Categories

Resources