【问题标题】:Python using string in dict() key?Python 在 dict() 键中使用字符串?
【发布时间】: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)

但是对于bc 键来说,这些不是固定的。这取决于其他值。

在我的情况下,评估分配给哪个字典的键是这样的:

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 是一个变量,例如bc
  • 你不能真正在一行中做到这一点。到目前为止,您拥有的解决方案是最好的方法。

标签: python dictionary


【解决方案1】:
main = {'a': 5}
dict_key1 = 'test_key'
dict_val1 = 5

some_new_dict = dict(main, other_key=5, **{dict_key1: dict_val1})

虽然,我发现您现在使用的两步法更具可读性,所以我认为它更好。

【讨论】:

    【解决方案2】:

    如果您想选择可读性,您可以使用复制,也许还可以将您的映射打包到行中:

    some_new_dict1 = main.copy()
    some_new_dict1[some_other_key] = 100
    some_new_dict1['b' if answer else 'c'] = 20
    

    顺便说一句,您的评论 #It can be greater than zero or lower than zero (but not zero). 对于您的 dict2_key 是错误的。 [not answer] 包括零,如果它对你的程序逻辑有影响的话。

    【讨论】:

    • 是的,它包括在内,但变量something 永远不是0,所以没关系。
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多