Python: Convert dictionary to bytes

You can use indent option in json.dumps() to obtain \n symbols: import json user_dict = {‘name’: ‘dinesh’, ‘code’: ‘dr-01’} user_encode_data = json.dumps(user_dict, indent=2).encode(‘utf-8′) print(user_encode_data) Output: b'{\n “name”: “dinesh”,\n “code”: “dr-01″\n}’

Does a std::map where the key is a pointer dereference pointers, or do you need a custom comparator?

The default implementation will compare the addresses stored by the pointers, so different objects will be considered as different keys. However, the logical state of the object will not be considered. For example, if you use std::string * as the key, two different std::string objects with the same text of “Hello” would be considered a … Read more

Deep merge dictionaries of dictionaries in Python

This is actually quite tricky – particularly if you want a useful error message when things are inconsistent, while correctly accepting duplicate but consistent entries (something no other answer here does..) Assuming you don’t have huge numbers of entries, a recursive function is easiest: def merge(a: dict, b: dict, path=[]): for key in b: if … Read more

How can I move a particular HashMap entry to the end of the map?

To answer your question in one sentence: Per default, Maps don’t have a last entry, it’s not part of their contract. And a side note: it’s good practice to code against interfaces, not the implementation classes (see Effective Java by Joshua Bloch, Chapter 8, Item 52: Refer to objects by their interfaces). So your declaration … Read more

Sorting a defaultdict by value in python

>>> sorted(cityPopulation.iteritems(),key=lambda (k,v): v[0],reverse=True) #1990 [(‘C’, [30, 10, 20]), (‘B’, [20, 30, 10]), (‘A’, [10, 20, 30])] >>> sorted(cityPopulation.iteritems(),key=lambda (k,v): v[2],reverse=True) #2010 [(‘A’, [10, 20, 30]), (‘C’, [30, 10, 20]), (‘B’, [20, 30, 10])] Note in python 3 you can’t automagically unpack lambda arguments so you would have to change the code sorted(cityPopulation.items(), key=lambda k_v: … Read more

Python argparse dict arg

Here’s another solution using a custom action, if you want to specify dict key pairs together comma-separated — import argparse import sys parser = argparse.ArgumentParser(description=’parse key pairs into a dictionary’) class StoreDictKeyPair(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): my_dict = {} for kv in values.split(“,”): k,v = kv.split(“=”) my_dict[k] = v setattr(namespace, self.dest, my_dict) parser.add_argument(“–key_pairs”, … Read more

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