How to get a random value from dictionary?

One way would be: import random d = {‘VENEZUELA’:’CARACAS’, ‘CANADA’:’OTTAWA’} random.choice(list(d.values())) EDIT: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be: country, capital = random.choice(list(d.items()))

In STL maps, is it better to use map::insert than []?

When you write map[key] = value; there’s no way to tell if you replaced the value for key, or if you created a new key with value. map::insert() will only create: using std::cout; using std::endl; typedef std::map<int, std::string> MyMap; MyMap map; // … std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value)); if ( ! res.second ) { cout … Read more

How to implement an ordered, default dict?

The following (using a modified version of this recipe) works for me: from collections import OrderedDict, Callable class DefaultOrderedDict(OrderedDict): # Source: http://stackoverflow.com/a/6190500/562769 def __init__(self, default_factory=None, *a, **kw): if (default_factory is not None and not isinstance(default_factory, Callable)): raise TypeError(‘first argument must be callable’) OrderedDict.__init__(self, *a, **kw) self.default_factory = default_factory def __getitem__(self, key): try: return OrderedDict.__getitem__(self, key) … Read more

Creating a dictionary from a csv file?

I believe the syntax you were looking for is as follows: import csv with open(‘coors.csv’, mode=”r”) as infile: reader = csv.reader(infile) with open(‘coors_new.csv’, mode=”w”) as outfile: writer = csv.writer(outfile) mydict = {rows[0]:rows[1] for rows in reader} Alternately, for python <= 2.7.1, you want: mydict = dict((rows[0],rows[1]) for rows in reader)

Hashing a dictionary?

Using sorted(d.items()) isn’t enough to get us a stable repr. Some of the values in d could be dictionaries too, and their keys will still come out in an arbitrary order. As long as all the keys are strings, I prefer to use: json.dumps(d, sort_keys=True) That said, if the hashes need to be stable across … Read more

Difference between defining typing.Dict and dict?

There is no real difference between using a plain typing.Dict and dict, no. However, typing.Dict is a Generic type * that lets you specify the type of the keys and values too, making it more flexible: def change_bandwidths(new_bandwidths: typing.Dict[str, str], user_id: int, user_name: str) -> bool: As such, it could well be that at some … Read more

How can I use if/else in a dictionary comprehension?

You’ve already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon: { (some_key if condition else default_key):(something_if_true if condition else something_if_false) for key, value … Read more

How to save a dictionary to a file?

Python has the pickle module just for this kind of thing. These functions are all that you need for saving and loading almost any object: with open(‘saved_dictionary.pkl’, ‘wb’) as f: pickle.dump(dictionary, f) with open(‘saved_dictionary.pkl’, ‘rb’) as f: loaded_dict = pickle.load(f) In order to save collections of Python there is the shelve module.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)