+ 1
How do I resolve this problem?
I am trying to create a dictionary class and it is only taking string as its keys but not integer. How to solve this? https://code.sololearn.com/civ63gWck6L1/?ref=app
17 Respostas
+ 4
Harsha S
def __setitem__(self, key, value):
if key in self.keys_:
i = self.keys_.index(key)
self.values_[i] = value
else:
self.keys_.append(key)
self.values_.append(value)
def __getitem__(self, key):
i = self.keys_.index(key)
return self.values_[i]
https://code.sololearn.com/c9unHrwR8JH9/?ref=app
+ 2
Do you accept "5" as key?
In this case a blind converting to str will do it.
+ 2
In this case
a) u can't work with set/get attribute or
b) u reserve a namespace for numerical attributes eg #5 #6 and convert to string.
+ 2
setattr(self, key, value)
Why do you even need this, if you already have two lists to store keys and values?
According to documentation, the second argument of setattr must be a string.
https://docs.python.org/3/library/functions.html#setattr
+ 2
If you want to be even more precise and similar to the API of the normal dict, you can even put this in the getter methods:
if key not in self.keys_:
raise KeyError
+ 2
Harsha S
Instead of recreating a dict, you can inherit from UserDict.
https://realpython.com/inherit-JUMP_LINK__&&__python__&&__JUMP_LINK-dict/#:~:text=Sometimes%2C%20the%20standard%20functionality%20of,with%20modified%20or%20new%20functionality.
+ 2
import json
from urllib.request import urlopen
url = "https://raw.githubusercontent.com/matthewreagan/WebstersEnglishDictionary/master/dictionary.json"
response = urlopen(url)
data_json= json.loads(response.read())
word = input("Enter word to see the meaning!\n").lower().strip()
meaning = data_json.get(word)
if meaning is None:
print (f"Your search \"{word}\" not found in the dictionary!")
else:
'''
for i in meaning:
if i.isdigit():
meaning = meaning .replace(i,i+"\n"
'''
print(meaning)
+ 1
Tibor Santa
I want to add key value pairs to the dictionary.
like dct[5] = 6
how do i achieve this with 2 lists without using setattr?
+ 1
Tibor Santa
thank you ☺
+ 1
Tibor Santa
yes, I will. Thank you.
+ 1
Bob_Li thank you
+ 1
PLZZ. Copy this code i write this code for you (Python)
https://www.sololearn.com/discuss/3075978/?ref=app
0
Oma Falk how do i get the value of 5 if i convert it to '5'?
what if I need to have both 5 and '5' as keys??
0
Vitaly Sokol
i got a "map not defined" error
- 1
Help
- 1
Please help me, I have a big problem regarding output
- 1
You know php I want to write specific codes