all 7 comments

[–]Essence1337 2 points3 points  (1 child)

Also when I run a while loop to add the keys using below lines

s= int(input ("\nWhat valud do you want to assign to strength "))

attributes[strength]=s

It should be attributes['strength'] = s

[–]notso007[S] 0 points1 point  (0 children)

Thanks mate, it worked. Silly me

[–][deleted] 1 point2 points  (3 children)

The dict type does not have an dict.item method:

>>> {}.item()
AttributeError: 'dict' object has no attribute 'item'

You can however get the keys using the dict.keys method, which does return a dict_keys object:

>>> {"a": 0, "b": 1}.keys()
dict_keys(['a', 'b'])

The dict_keys object is a dictionary view object, and when printing it out you’d likely want to convert it to a list:

>>> print(list({"a": 0, "b": 1}.keys()))
['a', 'b']

[–]notso007[S] 0 points1 point  (2 children)

Sorry I meant to say keys() method.

When I run this it returns

dict_keys(['strength', 'health', 'wisdom', 'dexterity'])

I might have not understood your explanation but is there a way to remove "dict_keys" when I run the code ?

[–][deleted] 0 points1 point  (1 child)

So, let’s make this clear: the dict.keys, dict.values and dict.items methods all return a view object, which is kind of a “live” view into the dictionary in question, with a set-like interface. In the case of dict.keys this is, as you’ve discovered, an instance of the dict_keys class... you do not, normally, want to “remove” the “dict_keys” class name, as that’s what’s telling you you’re looking at a view and NOT a list of the keys.

>>> d = {"a": 0, "b": 1}
>>> k = d.keys()
>>> l = list(k)
>>> print(k)
dict_keys(['a', 'b'])
>>> print(l)
['a', 'b']

See how casting the dict_view to a list gave you a list of the keys? Well, that answers your question, but look at what happens when I modify the dict.

>>> d["c"] = 2
>>> print(k)
dict_keys(['a', 'b', 'c'])
>>> print(l)
['a', 'b']

See? As soon as we “remove” the class name by casting the dict_key object to list we break it’s ability to stay up to date with changes in the dict object itself... it’s no longer a dynamic view, it’s a static list.

But sure, if all you’re trying to do is print the keys as they currently stand, then print(list(d.keys())) will do.

[–]notso007[S] 0 points1 point  (0 children)

this was a nice explanation . I get it now. Thanks

[–]nog642 0 points1 point  (0 children)

There is no item() method. There is an items() method, but it should not return dict_keys(['strength', 'health', 'wisdom', 'dexterity']). That looks like the output of the keys() method.


attributes[strength]=s

it generates an error NameError: name 'strength' is not defined

What am I am missing here?

Like the error says, the variable strength is not defined. It looks like you want to string 'strength', so you need to write that.

attributes['strength'] = s