How to convert a nested Python dict to object?

Update: In Python 2.6 and onwards, consider whether the namedtuple data structure suits your needs: >>> from collections import namedtuple >>> MyStruct = namedtuple(‘MyStruct’, ‘a b d’) >>> s = MyStruct(a=1, b={‘c’: 2}, d=[‘hi’]) >>> s MyStruct(a=1, b={‘c’: 2}, d=[‘hi’]) >>> s.a 1 >>> s.b {‘c’: 2} >>> s.c Traceback (most recent call last): File … Read more

What’s the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

For your needs, use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly). Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date … Read more

Proper way to initialize a C# dictionary with values

I can’t reproduce this issue in a simple .NET 4.0 console application: static class Program { static void Main(string[] args) { var myDict = new Dictionary<string, string> { { “key1”, “value1” }, { “key2”, “value2” } }; Console.ReadKey(); } } Can you try to reproduce it in a simple Console application and go from there? … Read more

Are dictionaries ordered in Python 3.6+?

Are dictionaries ordered in Python 3.6+? They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that’s guaranteed across other implementations of Python (and other … Read more

Filter dict to contain only certain keys?

Constructing a new dict: dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys } Uses dictionary comprehension. If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((your_key, old_dict[your_key]) for …). It’s the same, though uglier. Note that this, unlike jnnnnn’s version, has stable performance (depends only on number of … Read more

Python list of dictionaries search

You can use a generator expression: >>> dicts = [ … { “name”: “Tom”, “age”: 10 }, … { “name”: “Mark”, “age”: 5 }, … { “name”: “Pam”, “age”: 7 }, … { “name”: “Dick”, “age”: 12 } … ] >>> next(item for item in dicts if item[“name”] == “Pam”) {‘age’: 7, ‘name’: ‘Pam’} If … Read more

How to define hash tables in Bash?

Bash 4 Bash 4 natively supports this feature. Make sure your script’s hashbang is #!/usr/bin/env bash or #!/bin/bash so you don’t end up using sh. Make sure you’re either executing your script directly, or execute script with bash script. (Not actually executing a Bash script with Bash does happen, and will be really confusing!) You … Read more

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