Python's dict class in C++


A recreation of Python's dict class in C++


The class dict is a template:

template<key_type, val_type>
class dict

Usage is similar to Python:

dict<string,string> d;
d["foo"] = "bar";


val_type pop(key_type key)

Remove an item from from the dict and return its value

std::vector<std::pair<key_type, val_type>> items()

Return a vector containing every key-value pair in the dict

void clear()

Remove all key-value pairs in the dict

std::pair<key_type, val_type> pop_item()

Remove the most recently added key-value pair andd return it as a vector

std::vector<key_type> list_keys()

Return a vector containing all keys in the dict

std::vector<val_type> list_values()

Return a vector containing all values in the dict

key_type& get_key_by_value(val_type val)

Return a reference to a key by its value

Thanks for reading! Also, check out the project on Github!

the github repo is usually updated to the newest stable version within 48 hours

You are viewing a single comment. View All
DynamicSquid (5014)

Nice! Is there a way to sort it though?


@DynamicSquid I'm not sure what you mean by "sort through". If you mean getting an item by its index, I plan on adding that feature soon (probably tomorrow bc I have nothing better to do)

DynamicSquid (5014)

@ANDREWVOSS Oh, I just meant if there is a way to sort the dict. That way you can allow a user to iterate through it.


@DynamicSquid The dict is sorted in the order that the items were added. You can already iterate through list_keys(), list_values(), and items(). If I implement the indexing feature, that will add a way to iterate through the dict without exporting it as another datatype (So you could modify values as you iterate).


@ANDREWVOSS it would look something like this:

dict d<std::string,std::string>;
for (int i = 0; i < d.length(); ++i) {
  std::cout << d.index(i).key << d.index(i).val;
// 'key' would be a reference, so you could also reassign it, same with 'val'

@DynamicSquid I implemented the index feature, it works exactly like I outlined above.


@DynamicSquid Actually I had to change the implementation some. Turns out std::pair doesn't play well with references, so there is going to be two index functions, one to get a value, and another for a key. (So the feature won't be as simple as I had hoped, but it should work)