how to pass string as key in dictionary - python

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.

Related

Error with unhashable type while using TweetTokenize

I start by downloading some tweets from Twitter.
tweet_text = DonaldTrump["Tweets"]
tweet_text = tweet_text.str.lower()
Then in next step, we move with TweetTokenizer.
Tweet_tkn = TweetTokenizer()
tokens = [Tweet_tkn.tokenize(t) for t in tweet_text]
tokens[0:3]
Can someone explain to me and help me solve it.
I have been through similar questions that face similar errors but they provide different solutions.
Lists are mutable and can therefore not be used as dict keys. Otherwise, the program could add a list to a dictionary, change its value, and it is now unclear whether the value in the dictionary should be available under the new or the old list value, or neither.
If you want to use structured data as keys, you need to convert them to immutable types first, such as tuple or frozenset. For non-nested objects, you can simply use tuple(obj). For a simple list of lits, you can use this:
tuple(tuple(elem) for elem in obj)
But for an arbitrary structure, you will have to use recursion.

python: getting keys of a dictionary

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

How to accept a database and print out a list in python

So I have to create a simple program that accepts a database with a bunch of artists and their works of art with the details of the art. There is a given artist and I have to search through the database to find all the ones where they have to same artist and return them. I'm not allowed to use other built in functions nor import anything. Can someone tell me why its creating the error and what it means?
def works_by_artists(db,artists):
newlist = {}
for a in db.keys():
for b in db[artists]:
if a == b:
newlist.append(a);
return newlist
This prints out an error:
for b in db[artists]:
TypeError: unhashable type: 'list'
A dictionary can accept only some kinds of values as keys. In particular, they must be hashable, which mean they cannot change while in the dictionary ("immutable"), and there must be a function known to Python that takes the value and returns a nonnegative integer that somehow represents the integer. Integers, floats, strings, and tuples are immutable and hashable, while standard lists, dictionaries, and sets are not. The hash value of the key is used to store the key-value pair in the standard Python dictionary. This method was chosen for the sake of speed of looking up a key, but the speed comes at the cost of limiting the possible key values. Other ways could have been chosen, but this works well for the dictionary's intended purpose in Python.
You tried to execute the line for b in db[artists]: while the current value of artists was not hashable. This is an error. I cannot say what the value of artists was, since the value was a parameter to the function and you did not show the calling code.
So check which value of artists was given to function works_by_artists() that caused the displayed error. Whatever created that value is the actual error in your code.

Having trouble appending dictionary values to list in python

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.

TypeError: unhashable type python work around?

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.

Categories

Resources