2

I have a dictionary with four keys a,b,c,d with values 100,200,300,400

list1 = {'a':'100','b':'200','c':'300','d':'400'}

And a variable inputs.

inputs = 'c'

If inputs is c. The list1 dictionary has to be sorted based on it.

inputs = 'c'
list1 = {'c':'300','a':'100','b':'200','d':'400'}

inputs = 'b'
list1 = {'b':'200','a':'100','c':'300','d':'400'}
0

4 Answers 4

5

In Python3.7+ dict keys are stored in the insertion order

k ='c'
d={k:list1[k]}
for key in list1:
    if key!=k:
        d[key]=list1[key]

Output

{'c': '300', 'a': '100', 'b': '200', 'd': '400'}
Sign up to request clarification or add additional context in comments.

Comments

2

Seems like you just want to rearrange your dict to have the chosen value at the front, then the remaining keys afterwards:

dict1 = {'a':'100','b':'200','c':'300','d':'400'}

key = 'c'

result = {key: dict1[key], **{k: v for k, v in dict1.items() if k != key}}

print(result)
# {'c': '300', 'a': '100', 'b': '200', 'd': '400'}

The ** simply merges the leftover filtered keys with key: dict1[key].

Comments

1

If you just want to change the position to the first one a given value if it exists, it could be done in the following way:

list1 = {'a':'100','b':'200','c':'300','d':'400'}

inputs = 'c'

output = {}

if inputs in list1.keys():
    output[inputs] = list1.get(inputs)

for i in list1.keys():
    output[i] = list1[i]

Output;

{'c': '300', 'a': '100', 'b': '200', 'd': '400'}

Comments

0

Here's a one-liner:

d = {'a':'100','b':'200','c':'300','d':'400'}
i = input()

d = {i:d[i],**{k:d[k] for k in d if k!=i}}

print(list1)

Input:

c

Output:

{'a': '100', 'b': '200', 'd': '400', 'c': '300'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.