Posts

Showing posts with the label Dictionary

Adding Dictionaries Together, Python

Answer : If you're interested in creating a new dict without using intermediary storage: (this is faster, and in my opinion, cleaner than using dict.items()) dic2 = dict(dic0, **dic1) Or if you're happy to use one of the existing dicts: dic0.update(dic1) Here are quite a few ways to add dictionaries. You can use Python3's dictionary unpacking feature. ndic = {**dic0, **dic1} Or create a new dict by adding both items. ndic = dict(dic0.items() + dic1.items()) If your ok to modify dic0 dic0.update(dic1) If your NOT ok to modify dic0 ndic = dic0.copy() ndic.update(dic1) If all the keys in one dict are ensured to be strings ( dic1 in this case, of course args can be swapped) ndic = dict(dic0, **dic1) In some cases it may be handy to use dict comprehensions (Python 2.7 or newer), Especially if you want to filter out or transform some keys/values at the same time. ndic = {k: v for d in (dic0, dic1) for k, v in d.items()} >>> dic0 = {...

Convert A Pandas DataFrame To A Dictionary

Answer : The to_dict() method sets the column names as dictionary keys so you'll need to reshape your DataFrame slightly. Setting the 'ID' column as the index and then transposing the DataFrame is one way to achieve this. to_dict() also accepts an 'orient' argument which you'll need in order to output a list of values for each column. Otherwise, a dictionary of the form {index: value} will be returned for each column. These steps can be done with the following line: >>> df.set_index('ID').T.to_dict('list') {'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]} In case a different dictionary format is needed, here are examples of the possible orient arguments. Consider the following simple DataFrame: >>> df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]}) >>> df a b 0 red 0.500 1 yellow 0.250 2 blue 0.125 The...

Convert Map To JSON Object In Javascript

Answer : Given in MDN, fromEntries() is available since Node v12: const map1 = new Map([ ['foo', 'bar'], ['baz', 42] ]); const obj = Object.fromEntries(map1); // { foo: 'bar', baz: 42 } For converting object back to map: const map2 = new Map(Object.entries(obj)); // Map(2) { 'foo' => 'bar', 'baz' => 42 } I hope this function is self-explanatory enough. This is what I used to do the job. /* * Turn the map<String, Object> to an Object so it can be converted to JSON */ function mapToObj(inputMap) { let obj = {}; inputMap.forEach(function(value, key){ obj[key] = value }); return obj; } JSON.stringify(returnedObject) You could loop over the map and over the keys and assign the value function createPaths(aliases, propName, path) { aliases.set(propName, path); } var map = new Map(), object = {}; createPaths(map, 'paths.aliases.server.entry', 'src/test'); createPaths(ma...

Converting Xml To Dictionary Using ElementTree

Answer : The following XML-to-Python-dict snippet parses entities as well as attributes following this XML-to-JSON "specification": from collections import defaultdict def etree_to_dict(t): d = {t.tag: {} if t.attrib else None} children = list(t) if children: dd = defaultdict(list) for dc in map(etree_to_dict, children): for k, v in dc.items(): dd[k].append(v) d = {t.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}} if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.items()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]['#text'] = text else: d[t.tag] = text return d It is used: from xml.etree import cElementTree as ET e = ET.XML(''' <root> <e /> <e>text</e> <e name="va...

Can Python Dictionary Comprehension Be Used To Create A Dictionary Of Substrings And Their Locations?

Answer : The problem is that v[0] depends on the length or v[1] , which means that either the operation to generate v[1] would have to operate twice, or that the dictionary would have to be iterated over in order to fill in v[0] to replace the dummy value included the first time. Another problem is that dict comprehensions expect the entire key and value to be available immediately, which means that you would have to run a list comprehension to get all the indexes of the character, which means that the entire operation becomes O(n 2 ). The only optimization I would make would be to replace the creation of d so that you don't need to check for key containment. d = collections.defaultdict(lambda: [0, []]) It is scary, but (I added just offsets, number of occurrences you may get from list of offsets). Yes, it may be done In [83]: my_str = 'abcdabcxdabc' In [84]: n=3 In [85]: {substr: [my_str.replace(substr, ' '*n, c).index(substr) ...