当我将字符串元组创建为元组 的元素时,它可以正常工作,但是当我创建字符串元组作为<的元素时,它不起作用Python 3中的strong>字典 。
Python shell状态如下:
=============================== RESTART: Shell ===============================
>>> keys = ("one","two","three")
>>>
>>> TD1 = [["\0" for x in range(2)] for y in range(3)]
>>> TD1[0] = ("First","Tuple")
>>> TD1
[('First', 'Tuple'), ['\x00', '\x00'], ['\x00', '\x00']]
>>> #string tuples as an element of a tuple created
>>>
>>> TD2 = [["\0" for x in range(2)] for y in keys]
>>> TD2["one"] = ("First","Tuple")
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
TD2["one"] = ("First","Tuple")
TypeError: list indices must be integers or slices, not str
>>> #string tuples as an element of a dictionary not created
>>>
有人可以告诉我怎么做...我想创建字符串元组作为字典的元素。我想要一个像这样引用相同名称的结构:
&#34;颜色&#34; =(&#34; Red&#34;,&#34; Blue&#34;,&#34; Green&#34;,&#34; Yellow&#34;,&#34; Pink&#34;)
&#34;动物&#34; =(&#34; Lion&#34;,&#34; Horse&#34;,&#34; Kangaroo&#34;,&#34; Dog&#34;,&#34; Bull&#34;)
&#34;鸟&#34; =(&#34; Parrot&#34;,&#34;夜莺&#34;,&#34; Hawk&#34;,&#34; Sparrow&#34;,&#34; Eagle&#34;)
&#34;水果&#34; =(&#34; Mango&#34;,&#34; Apple&#34;,&#34; Cherry&#34;,&#34; Grapes&#34;,&#34; Banana&#34;)
答案 0 :(得分:4)
这里的问题是TD2是一个列表,而不是字典。如果你想获得一本字典,你可以使用dict comprehension:
TD2 = {y: ["\0" for x in range(2)] for y in keys}
注意大括号和key: value
表达式。
答案 1 :(得分:0)
这是代码但有效。你需要使字典成为字典。你的TD2是一个清单。
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Match update",
"body":"Arsenal goal in added time, score is now 3-0"
},
"android":{
"ttl":"86400s",
"notification"{
"click_action":"OPEN_ACTIVITY_1"
}
},
"apns": {
"headers": {
"apns-priority": "5",
},
"payload": {
"aps": {
"category": "NEW_MESSAGE_CATEGORY"
}
}
},
"webpush":{
"headers":{
"TTL":"86400"
}
}
}
}