0

how to get the key or values one by one from the dictionary?

For example:

dictionary = {}
if x found in y:
    name = "simply"
    dictionary[name]={}
    bang = {'abc','dsw','lol'}
    dictionary[name]={bang}
for k in (dictionary):
    print (k)

what if i only want to get the first key 'abc' ?

what method should i use since print(k[0]) is not working for me. it will only print the 1st letter for all the keys

when i call dictionary["simply"] it will show

abc

dsw

lol

What if I only wan to get abc for further steps?

Dsw Wds
  • 482
  • 5
  • 17

2 Answers2

1

Python dictionaries are unordered. If you want an ordered dictionary, try OrderedDict.

>> from collections import OrderedDict
>> d = OrderedDict()    
>> d['apple'] = 'red'  
>> d['banana']='white'     
>> d.items()[0]

>> output: ('apple', 'red')
0

You are making a set and not a dictionary. If you do dir with your set, you can see that there's no way to get a certain key by name from set. So you have to use a non in-built collection.

>>> dictionary={'abc','dsw','lol'}
>>> type(dictionary)
<type 'set'>
>>> dir(dictionary)
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>> dictionary.pop()
'dsw'
>>>

You can install ordered-set to do just that.

Do pip install ordered-set and then you can use it for your use case:

>>> from ordered_set import OrderedSet
>>> dir = OrderedSet(['abc','dsw','lol'])
>>> dir[0]
'abc'
schafle
  • 615
  • 4
  • 10