简体   繁体   English

访问特定的python defaultdict

[英]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 如何仅访问第一个索引为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] . 另一种可能性是改为使用defaultdicts的defaultdict,并访问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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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