简体   繁体   中英

python data structure: map<string, vector<int>>

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.

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.

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 OrderedDict of Lists .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM