63297

python data structure: map

Question:

Sorry for asking this newbie question.

In C++, I can have something like this:

map<string, vector<int>> m m["A1"].push_back(1); m["A1"].push_back(2); m["B3"].push_back(3); //etc

The thing is that I wanna plot it out with mathplot. Each vector will be sorting in according to their string value "A1", "B3", etc.

Can I implement something similar in python? Note that I will have to plot with mathplot. So accessing the vector should be very easy.

Answer1:

In Python, the equivalent of a hashmap is a Dict (in fact, most implementation of Dict are hashmaps). To ensure ordering across implementations, you will want to use an OrderedDict. A List is equivalent to a vector. Therefore, what you want is an <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">OrderedDict</a> of <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">Lists</a>.

from collections import OrderedDict // Create the dictionary d = {'A1': [1, 2], 'B2': [2, 3]} // Order it by key m = OrderedDict(sorted(d.items(), key=lambda t: t[0])) // Example of appending to one of the lists m['A1'].append(3) print(m)

This will print:

OrderedDict([('A1', [1, 2, 3]), ('B2', [2, 3])])

You can also add additional keys containing Lists like this:

m["B2"] = [2, 3, 5, 7]

You will then need to re-sort the OrderedDict.

A minor note: Dicts in Python aren't ordered; they happen to be ordered in very new versions of CPython 3, but that's an implementation detail. Therefore, OrderedDict is the most applicable datastructure here, to ensure that your code is portable. I'm mentioning this because many people are very excited about this feature of CPython, but it's not guaranteed to work everywhere.

Answer2:

Use a Dict :

m = {"A1" : [], "B3" : []} m["A1"].append(1) m["A1"].append(2) m["B3"].append(3)

Note that you need to insert the key first in the dictionary, otherwise it would show KeyError. If you want to add a new key, suppose "A2" here, simply do :

m["A2"] = []

To sort the dictionary according to its keys, use an OrderedDict :

m = OrderedDict(sorted(m.items(), key = lambda t : t[0]))

One more thing, only non-mutable items such as strings, tuples, int, etc. are allowed as keys in a python dictionary, you can't have a dictionary with a list like [1,2,3] as one of the keys.

Recommend

  • Android - passing hashmap through intent
  • Get object name of a class from the user in Java
  • Android: Creating custom class of resources
  • Serialize HashMap as root element with Simple
  • how access value of array list on Struts framework by properties file
  • FromJSON make a list from multiple fields
  • python re.compile and split with ÆØÅ charcters
  • Issue with static code in Android
  • Converting Dictionary to Dataframe with tuple as key
  • What other Adapters can I use for ListView?
  • ExtJS 4 Spring 3 file upload. Server sends bad response content type
  • How to prevent cross domain issues by proxying in IIS?
  • Bokeh custom ToolTips {safe} tag displays nothing
  • Performance difference between accessing local and class member variables
  • Access PCF DEV from external machine on same network as host
  • How to clear out the contents of a map when clear() method call throws UnsupportedOperationException
  • Update Search Results to Lazy Adapter in android
  • How to apply async task into this
  • Python getting common name from URL using ssl.getpeercert()
  • Activation Function choice for Neural network
  • import scipy.sparse failed
  • abstracting over a collection
  • Can't remove headers after they are sent
  • Android Studio Can't Find tools.jar
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • UWP/C# - Issue with AQS and USB Devices
  • Android changing fragment order inside FragmentPagerAdapter
  • where do I find the xml.dom python package for the python-2.6.0-8.9.28 and I have a suse/x86_64 vers
  • Python pickle not one-to-one: different pickles give same object
  • Jquery popup on mouse over of calendar control
  • C++ pointer value changes with static_cast
  • WPF ICommand CanExecute(): RaiseCanExecuteChanged() or automatic handling via DispatchTimer?
  • Ensure fsync did its job
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • How do I get HTML corresponding to current DOM tree?
  • How to create a file in java without a extension
  • What is the “return” in scheme?
  • Apache 2.4 and php-fpm does not trigger apache http basic auth for php pages
  • What are the advantages and disadvantages of reading an entire file into a single String as opposed
  • How to get NHibernate ISession to cache entity not retrieved by primary key