Pregunta

I'm new to python and I have become stuck on a data type issue.

I have a script which looks a bit like this dd = defaultdict(list) for i in arr: dd[color].append(i)

which creates a default dict which resembles something along the lines of

dd = [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

However I need to now access the first list([2,4]). I have tried

print(dd[0])

but this game me the following output

[][][]

I know the defaultdict has data in it as I have printed it in its entirety. However other than access the first item by its dictionary index I don't know how to access it. However, other than access the list by the dictionary key I don't know how to get it. However, I don't know the name of the key until I populate the dict.

I have thought about creating a list of lists rather than a defaultdict but being able to search via key is going to be really usefull for another part of the code so I would like to maintain this data structure if possible.

is there a way to grab the list by an index number or can you only do it using a key?

¿Fue útil?

Solución 2

Note that a dictionary in Python is an unordered collection. This means that the order of keys is undefined. Consider the following example:

from collections import defaultdict
d = defaultdict (int)
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
d['e'] = 5
print (d)

My Python2 gives:

defaultdict(<type 'int'>, {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4})

Python3 output is different by the way:

defaultdict(<class 'int'>, {'c': 3, 'b': 2, 'a': 1, 'e': 5, 'd': 4})

So, you will have to use some other means to remember the order in which you populate the dictionary. Either maintain a separate list of keys (colors) in the order you need, or use OrderedDict.

Otros consejos

You can get a list of keys, pick the key by index, then access that key.

print(dd[dd.keys()[0]])
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top