【发布时间】:2016-02-29 14:04:14
【问题描述】:
假设我有这个基本字典:
main = {'a': 10}
然后我有另外两个使用main 作为起点的字典,如下所示:
some_new_dict1 = dict(main, b=20, some_other_key=100)
some_new_dict2 = dict(main, c=20, some_other_key2=200)
但是对于b 和c 键来说,这些不是固定的。这取决于其他值。
在我的情况下,评估分配给哪个字典的键是这样的:
some_map = {True: 'b', False: 'c'}
# Evaluate if its true or false
answer = something > 0 # something is variable that changes.
#It can be greater than zero or lower than zero (but not zero).
dict1_key, dict2_key = some_map[answer], some_map[not answer]
现在我有这些字符串形式的键,但我不知道如何通过dict 分配它。如果可能的话。
所以现在我正在这样做:
some_new_dict1 = dict(main, some_other_key=100)
some_new_dict1[dict1_key] = 20
# Same for another dict
所以基本上我需要创建字典,然后用那个键/值对更新它,即使我在创建那个字典之前知道那个键/值对。有没有更好的办法?
【问题讨论】:
-
你正在做的可能是最易读的方法。你可以做
some_new_dict1 = dict([(dict1_key, 20), ("some_other_key", 100)] + main.items()),但这真的值得吗? -
不可以用
update这个方法吗? -
我没有得到这个问题,如果您已经知道键/值,为什么不在创建字典时将其添加到字典中?
some_new_dict1 = dict(main, some_other_key=100, dict1_key = 20) -
@TomásGlaría
some_other_key是一个变量,例如b或c。 -
你不能真正在一行中做到这一点。到目前为止,您拥有的解决方案是最好的方法。
标签: python dictionary