+ 10
How i can make dictionary
withe .key () and value
7 odpowiedzi
+ 41
keys() is usually used to return a list of all the dictionary keys in arbitrary order.
Instead, you can use :
1. dict() e.g
d=dict(lang='python', extension='.py')
#printing d out gives, {'lang': 'python', 'extension': '.py'}
2. dictionary comprehension.
e.g
squares ={x:x**2 for x in range(3,7)}
print(squares)
# gives out the key 'x', with the corresponding square of 'x', as value , within the given range :
in this case :
{3: 9, 4: 16, 5: 25, 6: 36}
3.Now, to retrieve the keys in the above dictionary using keys()
do this :
squares.keys()
#gives out :
dict_keys ([3, 4, 5, 6])
#I Hope this is useful to you.
+ 6
Litteral assignements:
myDict1 = {} # empty dict
myDict2 = {'keyname1':42, 'keyname2':'value' }
Adding key/value pairs at run time in same way that you update a key
myDict1['key'] = 'the value to assign -- not necessarly a string, onviously'
You can get a specific key value with:
value = myDict2['keyname1'] # 42
.. or with the safer get() method wich avoid key error for undefined keys:
value = myDict1.get('undefinedkey',42)
(second parameter is the default value to return if key doesn't exist ;))
+ 5
@Reachard:
No upvotes for real answers, but 'best answer' mark set to latest unrelated answer?
WTF? @@
[edit]
... unrelated answer (what's app number) now deleted and best answer mark set to related one ^^
+ 5
Helping to get justice
+ 4
@visph I ain't even gonna try to understand... Also posting a phone number on a public website... 🤔
+ 4
Visph you are pyrely pissed at washika's skills
+ 4
@S Vengat:
@washika deserve the best answer, I have no problem with that... because he fully explain use of dictionnaries, while I only answer to the specific unclear question about 'how make a dictionary' ('with .key () and value' wasnt enough explicit for me :P)