reading inversed a dictionary python - python-3.x

I have this code in python 3.7
dictionnaire = {'a':'url1', 'b':'url2', 'c': 'url3'}
for key, value in dictionnaire.items():
print(key + ' ' + value)
the result is :
a url1
b url2
c url3
but i want this result
c url3
b url2
a url1
Thank you very much for your help

You can convert the dictionary items to a list, in order to reverse it. You've two ways:
Using reversed function:
for k,v in reversed(list(dictionnaire.items())):
print(k,v)
Using reverse on the list object:
l = list(dictionnaire.items()).reverse()
for k,v in l:
print(k,v)

One way to do it is by extracting keys from dictionary and reverse it.
keys = list(dictionnaire.keys())
Then use this list in reverse order to get the desired output.
for k in keys[::-1]:
print(k, dictionnaire[k])

convert to list
dic_list = list(dictionnaire.items())
reverse
dic_list.reverse()
read
for k, v in dic_list:
print(k + ' ' + v)

Related

Iterate through dictionary by indexes

How to bypass python out of box mechanism when an order of items() in the loop does not correspond to the order it supposes to be?
st = 'Tree'
freq = Counter(st)
sorted(freq.items(), key=lambda item: item[1])
arr = []
for k, v in freq.items():
for i in range(v):
arr.append(k)
I expect to get in the first iteration pair: ('e', 2), but instead it is ('t', 1).
But sorting was applied to dictionary at row 3.
How to iterate dictionary in way it is sorted? (without applying underhood re-order)
UPD. The question has already been answered, however, will be good to know why dictionaries implemented in Python3 in that way.
sort by keys:
a = dict(b=3, c=5, a=10)
for k in sorted(a):
print(f"{k}: {a[k]}")
and if you want to sort them by the values:
a = dict(b=3, c=5, a=10)
for k, v in sorted(a.items(), key=lambda item: item[1]):
print(f"{k}: {a[k]}")

Pop element at the beginning or at the last from dict in python3

Collection module in python has a datatype OrderedDict(), which enables us to save the key value pairs in the same order as they were inserted in dict. It has a method popitem, which allows us to pop items at the beginning or at the last
dict.popitem(last = True)
dict.popitem(last = False)
The default dict in python 3 also works as OrderedDict(), i.e., it maintains the order of key value pairs as they were inserted. But how to remove the first or the last element from this dict as in OrderedDict(), without using the traditional for loop for accessing the key value pair as
for key, value in dict:
dict.pop(key)
break
I just want to know if there is any inbuild function for popping the first or the last element in default dict of python 3 as in OrderedDict(). I searched but couldn't find any.
Since Python 3.6, dict.popitem always acts as a LIFO like OrderedDict.popitem(last=True) does.
But while there is no direct support from dict to make the popitem method pop from the front of the dict, you can simulate the FIFO behavior of OrderedDict.popitem(last=False) such as:
d = OrderedDict(a=1, b=2)
k, v = d.popitem(last=False) # k = 'a', v = 1
by getting the first key of the dict and then popping that key for its value:
d = {'a': 1, 'b': 2}
k = next(iter(d)) # k = 'a'
v = d.pop(k) # v = 1

How do I properly convert a string to a list

I have a function that returns a message as a string as follows:
l = ['["sure","kkk"]', '["sure","ii"]']
I have tried to remove the "'" character through an iteration but its not working for me.
This is my code:
print([item.replace('\'["','"').replace('"]\'','"') for item in l])
Is there a better way to do this since I want the results as this:
l = [["sure","kkk"], ["sure","ii"]]
Those are JSON encoded strings, so you should use the json API for that and not try to parse it "yourself":
import json
l = ['["sure","kkk"]', '["sure","ii"]']
l = [json.loads(s) for s in l]
print(l) # [['sure', 'kkk'], ['sure', 'ii']]
Can also be achieved with map instead of list comprehension:
l = list(map(json.loads, l))
Alternatively, you can also use ast.literal_eval (see the docs) as follows:
import ast
l = ['["sure","kkk"]', '["sure","ii"]']
l = [ast.literal_eval(s) for s in l]
print(l) # [['sure', 'kkk'], ['sure', 'ii']]

Convert elements in ONE list to keys and values in a dictionary

I'm looking for a way to convert a list to a dictionary as shown below. Is this possible? Thanks in advance.
list = ["1/a", "2/b", "3/c"]
dict = {"1": "a", "2": "b", "3": "c"}
Of course it is possible.
First, you can split an element of the list with e.split("/"), which will give a list for example splitted = ["1", "a"].
You can assign the first element to the key and the second to the value:
k = splitted[0]
v = splitted[1]
or another way to express that:
k,v = splitted
Then you can iterate over your list to build your dict, so if we wrap this up (you should not call a list list because list is a type and an already existing identifier:
d = {}
for e in elements:
k,v = e.split("/")
d[k] = v
You can also do that in one line with a dict comprehension:
d = {k:v for k,v in [e.split("/") for e in elements]}
Yes you can.
If you want to have everything after the '/' (i.e. 2nd char), you can do:
dict = {c[0]:c[2:] for c in list}
If you want to have everything after the '/' (but may not be the 2nd char), you can do:
dict = {c[0]:c.split('/')[1] for c in list}
It really dependes on the input you have and what output you want
You can do like this.
lista = ["1/a", "2/b", "3/c"]
new_dict = {}
for val in lista:
new_dict.update({val[0]:val[2]})
print(new_dict)
Try this
list = ["1as/aasc", "2sa/bef", "3edc/cadeef"]
dict = {i.split('/')[0]:i.split('/')[1] for i in list}
Answer will be
{'1as': 'aasc', '2sa': 'bef', '3edc': 'cadeef'}
I have given a different test case. Hope this will answer your question.

python3 value returned wrong with container variable

I meet a code that failed to meet my expectation. Details as below:
a = ['name']
b = [('name=cheng',),('name=huang',),('name=pan',)]
Dict = {}
c = []
for i in range(0,3):
for j in range(0,1):
Dict[a[j]] = b[i][j]
c.append(Dict)
print(c)
>>> [{'name':'name=pan'},{'name':'name=pan'},{'name':'name=pan'}]
what i expected should be
>>> [{'name':'name=cheng'},{'name':'name=huang'},{'name':'name=pan'}]
So could you please tell me how to solve the issue ?
You are changing the value of Dict in place and not creating a new dictionary every time. Each iteration of the loop, you are setting Dict["name"] equal to one of the elements in b and then appending it to the list. The next iteration of your loop changes dict in place (meaning the previous version you appending to c will also be changed). The result is that your list c is filled with 3 exact copies (exact same location in memory) of the dictionary created in the final iteration of the loop.
How do you fix this? Make a new dictionary every time.
a = ['name']
b = [('name=cheng',),('name=huang',),('name=pan',)]
c = []
for i in range(0,3):
for j in range(0,1):
temp_dict = {a[j]: b[i][j]}
c.append(temp_dict)
print(c)
Result:
[{'name': 'name=cheng'}, {'name': 'name=huang'}, {'name': 'name=pan'}]
You use the same value of Dict for all of the iterations of the loop. So all of the dictionaries are the same. You just have three copies of the same dictionary in the list.
If you move the Dict = {} statement into the loop, it will be fixed.
a = ['name']
b = [('name=cheng',),('name=huang',),('name=pan',)]
c = []
for i in range(0,3):
Dict = {}
for j in range(0,1):
Dict[a[j]] = b[i][j]
c.append(Dict)
print(c)
Or more Pythonic:
keys = ['name']
values_list = [('name=cheng',), ('name=huang',), ('name=pan',)]
result = []
for values in values_list:
result.append(dict(zip(keys, values)))
print(result)
This works by using the zip builtin which does the same thing as [(x[i], y[i]) for i in range(min(len(x), len(y))] without needing to keep track of the indices or lengths.
The dict class can build a dictionary from a list of tuples, which is what this solution uses.

Resources