Frage

I have a list of tuples sorted by the keys which are binary numbers as string types.

This is how it looks now

('000', 'Jo')
('001', 'Ja')
('010', 'Ji')
('011', 'Je')
('100', 'Ju')
('101', 'Jy')
('110', 'Jl')
('111', 'Jk')

But now I want the characters in the strings to look like

(000, 'jo')
(100, 'ja')
(010, 'ji')
(110, 'je')
(001, 'ju')
(101, 'jy')
(011, 'jl')
(111, 'jk')

But to still be with the same value.

So, how do I flip the first element in the tuple to get the output?

War es hilfreich?

Lösung

Your keys aren't binary numbers, they're strings representing binary numbers. To reverse a string, you can use slice notation:

s = s[::-1]

To reverse all of the (str) keys in a dictionary:

dct = {k[::-1]: v for k, v in dct.items()}

To simultaneously calculate the numerical values using the int(s, 2) notation:

dct = {int(k[::-1], 2): v for k, v in dct.items()}

Andere Tipps

if the keys are binary numbers instead of strings as in the original question - thus something like

mydict = {
    0b1100111: 'Jo'
}

then they can be reversed in this way:

dct = {'{0:b}'.format(k)[::-1]: v for k, v in mydict.items()}

but the new keys will be strings (this to let you observe the reversed bits). If you want them to remain numbers, you can convert them back to integers:

dct = {int('{0:b}'.format(k)[::-1], 2): v for k, v in mydict.items()}

(supposing you are using python 2.6+)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top