Can Python dictionaries to be as handy as PHP array?

Recently, I'm working on a Python-based project and facing a issue with dictionaries. In PHP I can easily create a multiple dimension array by the following instruction:

$user = "Tom";
$type = "New";
$userlist[$user]['count'] += 1;
$userlist[$user][$type] += 1;

PHP will create a new element within an array if it doesn't exist, which is very convenient for coding. Can Python dictionaries provide the same and handy function as PHP?

Answers


Python does not magically instantiate dictionaries as PHP does; however, with a bit of forethought, you can make it do what you want.

from collections import defaultdict, Counter

users = defaultdict(Counter)

users['Tom']['Count'] += 1
users['Tom']['New'] += 1

(also, calling a variable "somethinglist" when it's not a list is probably a bad idea, and type is a Python keyword, so don't use it as a variable name either!)


You can use Python's defaultdict (as this answer suggests):

from collections import defaultdict
user = "Tom"
type = "New"
userlist = defaultdict(lambda: defaultdict(int))
userlist[user]['count'] += 1
userlist[user][type] += 1

Need Your Help

Motorola MC2180 EMDK - Getting scanned data

c# visual-studio-2008 barcode-scanner motorola-emdk

I've been working on trying to get scanned data from Motorola MC2180. I know this is basic but I am a beginner and never touched a PDA before. I can get it to scan but the result data is still null...

Double and triple pointers in C

c pointers memory-management pointer-to-pointer

I have a small program as shown below.This program is an attempt to better understand pointers in 'C' how variables are arranged in memory.