When I do dict.keys() in python3, I do not get a list, but an object of class dict_keys. Why is this and what can I do with this object? How to get the list?
Example code: type(dict(sape=4139, guido=4127, jack=4098).keys())
I wonder if this result is intentional and why?
I called matplotlib.plot(d.keys(),....) and got an error.
dict.keys returns a dict_keys object, which is an iterable object.
So, you can either convert it to a list using:
keys = list(dict.keys())
Or, you can simply iterate over the dict_keys object, like it was intended:
for key in dict.keys():
print(key)
In your example, it will print out:
sape
guido
jack
Related
i want to parse dictionary dynamically
here i'm trying to get the name of key dynamically and storing that key in variable and call dictionary using those variable
so far i tried this
var=users.to_dict()
z=var.keys()
y=z[0]
x=var[str(y)]['Scheme name']
when i pass str(y) it giving error
y=x[0]
TypeError: 'dict_keys' object does not support indexing
is there any better ways to this. please let me know
you cannot index 'dict_keys' but if you parse them to 'list'
var=users.to_dict()
z=list(var.keys())
y=z[0]
x=var[str(y)]['Scheme name']
it should work
y=z[0]
is where your error is.
var.keys() doesn't return a list, it returns a dict_keys, which doesn't support indexing. You can convert it to an list and then index:
y = list(x)[0]
However, z = list(var) will have the same effect (list of keys) and is a little more direct.
A dict_keys behaves this way because it's a view object. It's an iterable whose contents change if the underlying dictionary changes. The result of casting it as a list (or casting the dictionary as a list) is that it's no longer connected to dictionary.
Dictionary So in python I have a dictionary that is composed of a name for the key and a class object associated with the name as the object. I need to append these objects to a list one by one from the dictionary, however when I attempt to use a for loop to do so it only appends the same object over and over agian. When I try to append dict.values(), I have them appended to a list but with the word dict_values being the first thing in the list when it should only be the values themselves. Does anybody have any ideas as to how to properly append these values? I have been using
for value in playerDict.values():
basicList.append(playerDict.values)
print(basicList)
to try and append the values to the list called basicList, however every time it appends the same object and after a few iterations the list simply looks like
[<built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48>]
Where am I going wrong in appending the object values. Sorry for the basic question I am pretty new to python.
Try doing this:
for value in playerDict.values():
basicList.append(value)
print(basicList)
Rather than:
for value in playerDict.values():
basicList.append(playerDict.values)
print(basicList)
When you try to append playerDict.values into the list, you were effectively trying to append value of the playerDict object in the object form and not what you stored in the key of the dictionary (and hence you were getting [<built-in method values of dict object at 0x103a03d48>, <built-in method values of dict object at 0x103a03d48> ). Whereas, when you append value, it appends the actual values of the keys stored in your dictionary.
Hope, it helps.
I want to update the DiseaseScenario.conn[newKey] which is a set but i keep getting the error not hashable. Is there a way around this?
DiseaseScenario.conn={}
for items in dictList:
for key,value in items.iteritems():
flag=1
for newKey,newValue in DiseaseScenario.conn.iteritems():
if key==newKey:
//***************************///
//geting the error Unhashable type
tempValue=[value,newValue]
DiseaseScenario.conn[newKey].remove(value)
DiseaseScenario.conn[newKey].add(tempValue)
//*******************************************//
flag=0
if flag==1:
DiseaseScenario.conn[key]=value
print DiseaseScenario.conn
You are trying to put a list in a set. You can't do that, because set items need to have a fixed hash, which mutable (changeable) builtin python types do not have.
The simplest solution is to just change your list to a tuple (a tuple is kind of like a list that can't be changed in-place). So change:
tempValue=[value,newValue]
to:
tempValue=(value,newValue)
That, of course, assumes value and newValue are not lists or other mutable types.
I'm simply trying to access the output from a variable named parser which is outputting a dictionary of information in it like:
{u'param': [u'6'], u'booID': [u'911'], u'animal': [u'cat']}
How can I access each parameter, and loop through each outputting the key value?
I tried, a number of different things including:
for parsed_val in parser:
print parsed_val + parsed_val.keys()
but this throws a AttributeError of AttributeError: 'unicode' object has no attribute 'keys'.
Thank you!
for key, value in parser.iteritems():
print key, value
Iterating through a dictionary iterates through its keys.
You'll want to iterate over dict.items(), which iterates over a list of (key,pair) tuples.
You can also use dict.iteritems (on python 2.x), which avoids creating a list and iterates directly over the dictionary
Alternative method:
for key in parser.keys():
print(str(key) + ': '+str(parser[key]))
dict.keys() is a list of all keys.
dict.items() is a list of of key/value pairs.
dict.iteritems is an iterable object of dict.items().
I was looking for ways to sort a dictionary and came across this code on a SO thread:
import operator
x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
How does this code work?
When I call iteritems() over a dictionary I get this:
<dictionary-itemiterator object at 0xf09f18>
I know that this is a reference, but how do you use it?
And afaik, in sorted(a,b), as is supposed to be the thing you want to sort, and b would be the indicator for sorting right? How does itemgetter(1) work here?
operator.itemgetter(1) is equivalent to lambda x: x[1]. It's an efficient way to specify a function that returns the value at index 1 of its input.
.iteritems() is a method of a dictionary that returns an iterator over the entries in the dictionary in (key,value) tuple form.
iteritems() is just like items(), except it returns an iterator rather than a list. For large dictionaries, this saves memory because you can iterate over each individual element without having to build up the complete list of items in memory first.
sorted accepts a keyword argument key which is a function used to determine what to compare by when sorting something. In this case, it is using operator.itemgetter, which is like the function version of doing something[1]. Therefore, the code is sorting on the [1] item of the tuples returned by items(), which is the value stored in the dictionary.
Most python built-ins which deal with lists or list like objects also accept iterators, these are like a pointer into the list, which you can advance to the next item in the list with the next() member function. This can be very convenient for infinite lists or very large lists, (either many elements or very large elements,) to keep memory usage down. See http://docs.python.org/library/stdtypes.html#iterator-types
iteritems() gives an iterator into the list of items in the dictionary.