字符串键比Python字典中的元组键快或慢

时间:2018-10-12 04:14:22

标签: python dictionary tuples key

我想创建一个Python字典,其键是来自两个或多个变量的组合,我想知道字符串组合更好还是元组更好?

例如:

a = 1 
b = 2
str_key = str(a)+str(b)
tuple_key = (a,b)

dict[str_key]dict[tuple_key]哪个更好?

1 个答案:

答案 0 :(得分:-1)

带有字符串键的字典

In [9]: a = {'12': 'test', '23': 'test', '56': 'test', '45': 'test', '34': 'test', '01': 'test', '89'
   ...: : 'test', '67': 'test', '910': 'test', '78': 'test'}

In [10]: % timeit [k for k,v in a.items()]
1000000 loops, best of 3: 1.49 µs per loop

带元组键的字典

In [14]: b={(0, 1): 'test', (1, 2): 'test', (6, 7): 'test', (5, 6): 'test', (7, 8): 'test', (8, 9): '
    ...: test', (4, 5): 'test', (2, 3): 'test', (9, 10): 'test', (3, 4): 'test'}

In [15]: % timeit [k for k,v in b.items()]
1000000 loops, best of 3: 1.36 µs per loop

显然元组是赢家