简体   繁体   中英

Accessing specific python defaultdict

Say I have a defaultdict with values:

x = defaultdict(int)
x[a,1] = 1
x[a,2] = 2
x[a,3] = 3
x[b,1] = 4
x[b,2] = 5
x[b,3] = 6
x[c,1] = 7
x[c,2] = 8
x[c,3] = 9

How do I access only those elements with the first index as c

Or rather, how do I implement something like this:

for key2 in x[,c]:
    print key2

Defaultdicts, like ordinary dicts, don't have any special slicing behavior on the keys. The keys are just objects, and in your case they're just tuples. The dict doesn't know or enforce anything about the internal structure of the keys. (It's possible to have different keys with different lengths, for instance.) The simplest way to get what you want is this:

for key in x.keys():
   if key[0] == 'c':
       print key, x[key]

Another possibility is to instead use a defaultdict of defaultdicts, and access the elements like x['c'][1] .

You can also use the following, thats a bit faster on my computer: Also, i don't know your usecase, but the data structure you have chosen isn't particulary efficient to query.

for i,e in x:
    if i=='c':
        print (i,e),x[(i,e)]

Test:

def func1():
    for key in x.keys():
       if key[0] =='c':
           return key, x[key]
def func2():
    for i,e in x:
        if i=='c':
            return (i,e),x[(i,e)]



timeit func1()

100000 loops, best of 3: 1.9 us per loop


timeit func2()
1000000 loops, best of 3: 1.56 us per loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM