英文:
How to parse key's uisng .format in dictionary
问题
试图使用 .format 从字典中获取值,
~~~
test_dict={'name':'John'}
input_value='name'
value= test_dict[input_value]
print(value)
~~~
但它会抛出错误,
~~~
TypeError: unhashable type: 'dict'
~~~
我无法找到这个简单程序的解决方法。
英文:
I am trying to fetch the value from a dictionary using .format
test_dict={'name':'John'}
input_value='name'
value= test_dict[{}].format(input_value)
print(value)
But it throw the error says
TypeError: unhashable type: 'dict'
i am not able to find a solution to this simple progam
答案1
得分: 1
这是正确的格式:
test_dict={'name':'John'}
input_value='name'
value= test_dict['{}'.format(input_value)]
print(value)
#John
英文:
This is the correct format:
test_dict={'name':'John'}
input_value='name'
value= test_dict['{}'.format(input_value)]
print(value)
#John
答案2
得分: 0
我不知道为什么需要以这种方式构建密钥,但我进行的效率测试显示这是最低效的方式。
import sys
sys.version # 3.10.11 (main, Apr 5 2023, 14:15:10) [GCC 9.4.0]
测试1(format
):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict['{}'.format(input_value)]
# 191 ns ± 32.4 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
测试(% 运算符):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict['%s' % input_value]
# 154 ns ± 43.3 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
测试(f-string
):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict[f'{input_value}']
# 123 ns ± 19.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
测试(无字符串格式化):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict[input_value]
# 96.8 ns ± 1.48 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
英文:
I don't know why it was necessary to build the key in this way, but the efficiency tests I conducted showed that this is the most ineffective way.
import sys
sys.version # 3.10.11 (main, Apr 5 2023, 14:15:10) [GCC 9.4.0]
Test1 (format
):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict['{}'.format(input_value)]
# 191 ns ± 32.4 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Test (% Operator):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict['%s' % input_value]
# 154 ns ± 43.3 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Test (f-string
):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict[f'{input_value}']
# 123 ns ± 19.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Test (without string formating):
%%timeit
test_dict={'name':'John'}
input_value='name'
value = test_dict[input_value]
# 96.8 ns ± 1.48 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论