[Tutor] Question about about PEP8
Peter Otten
__peter__ at web.de
Tue Jul 7 04:33:46 EDT 2020
Alan Gauld via Tutor wrote:
> On 07/07/2020 07:45, Manprit Singh wrote:
>> *case 2 ) I have to remove and print each item of dict in LIFO order :*
>>
>> d = {"A":9, "B":6, "C":3}
>> while d:
>> x = d.popitem()
>> print(x)
>
> And that will work too, but unless you really need to empty the dict
> (or even if you do) a more pythonic approach would be:
>
> for x in d.items():
To get LIFO order:
for x in reversed(d.items()):
> print(x)
>
> d = {} # if you really need an empty dic
>
> It's not any shorter, in fact slightly more characters,
> but it avoids using a while loop for iterating a sequence.
More information about the Tutor
mailing list