开发者

How can I define an array in Python with undefined keys?

searchindexnodes = []
searchindexnodes[1036开发者_如何学运维592] = 'Apparel'
searchindexnodes[672123011] = 'Apparel'
searchindexnodes[165796011] = 'Baby'

This doesn't appear to be working. Any thoughts?


I think a better solution would be to use a dictionary. If you wanted a list with empty elements you'd be creating a list with over 100,000,000 elements which would be a huge waste of memory.

searchindexnodes = {}
searchindexnodes[1036592] = 'Apparel'

Python implements searching quickly in dictionary data structures. You could check if an element is present by doing something like

if 1036592 in searchindexnodes:
    print "It's there!"

Edit to iterate through the whole list you can do something like if you want the key and value

for key, value in searchindexnodes.items():
    print "{0} --> {1}".format(key,value)

otherwise what's below will loop through each key

for key in serchindexnodes:
    print key


use a dictionary for that:

searchindexnodes = {}
searchindexnodes[1036592] = 'Apparel'
searchindexnodes[672123011] = 'Apparel'
searchindexnodes[165796011] = 'Baby'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜