I Didn't Know Dictionaries Could Do THIS In Python

preview_player
Показать описание
I didn't know dictionaries could do this in Python. #code #python #programming
Рекомендации по теме
Комментарии
Автор

I find this to be really more dangerous than useful ^^

julienb.
Автор

dict expects an iterable of two-element tuples. But it is duck-typed, so as long as your iterable yields a series of objects of length 2, it works on them! For each x in the iterable, dict takes x[0] as the key and x[1] as the value.

scottclowe
Автор

I wasn't aware of this either, but it does make sense. Strings can be seen as a sequence of characters, similar to a list, and the dict function can convert a list of two elements into a dictionary. Therefore, if you have a list of strings where each string consists of two characters, it can be considered a list of two-element sequences suitable for conversion into a dictionary.

nogamenolife
Автор

This is because it expectes an iter of iters, with the inner iter having a len of 2, this a tuple if strings, each being pairs of chars, will work

AlyceIsFree
Автор

I didn't know it too but that's kinda hard to use, very cool though

AkivaB
Автор

And for this to work the string length of the values element must exactly be equal to 2 for each. This means it won't work with a value like "Jan1" or "D12" but only "J1" and "D1" likes.

mubarakdederi
Автор

This make sense because String is just a list of Chars(Characters)

theplant
Автор

I am perfectly cool with not knowing this or using it ever 😂

Deerbruh
Автор

do not to this .. be explicit with your tuples and their k, v alignment

DeviantFox
Автор

It's almost like a string is just an array of characters.

bluesquare
Автор

Cool, but unnecessarily obfuscated to anyone reading through code and not knowing this technique

decky
Автор

python is full of surprises and as a high level language either though I know lots of other languages, but I wish to spend my time on python, Dictionaries in python are incredibly efficient O(1) in most operations . and they got even better after 3.8, they have now ordered dictionaries by themselves.

xzex
Автор

This works with any iterable of [iterable of lenght 2], so a more useful example would be :
entries = [("A", 13), ("B", 42), ("C", 69)]
print(dict(entries))
{'A': 13, 'B': 42, 'C': 69}

loic.bertrand
Автор

if you change values = ('a1', 'b2', 'b3') then you get {'a': '1', 'b': '3'}. hmm interesting

sussapiindia
Автор

What if the tuple will be with more than 2 characters each? Like ('ab1', 'cd2', 'ef3')

colourfulyoker
Автор

And then they say javascript is weird 😅

netero
Автор

Wow, i didn't know about that one. Thanks!!!

lfbicalho
Автор

That's nice until you input 'd11' and everything goes bananas. Never let the compiler guess. That's why floats are so bad.

WifeWantsAWizard
Автор

that's nicer than:
{k: v for k, v in ('a1', 'b2', 'c3')}

DrDeuteron
Автор

Syntatic sugar to sabotage code review 😂

konstantin