Can somebody explain this code ?
l3 = [ {'from': 55, 'till': 55, 'interest': 15}, ]
l4 = list( {'from': 55, 'till': 55, 'interest': 15}, )
print l3, type(l3)
print l4, type(l4)
OUTPUT:
[{'till': 55, 'from': 55, 'interest': 15}] <type 'list'>
['till', 'from', 'interest'] <type 'list'>
When you convert a dict
object to a list, it only takes the keys.
However, if you surround it with square brackets, it keeps everything the same, it just makes it a list of dict
s, with only one item in it.
>>> obj = {1: 2, 3: 4, 5: 6, 7: 8}
>>> list(obj)
[1, 3, 5, 7]
>>> [obj]
[{1: 2, 3: 4, 5: 6, 7: 8}]
>>>
This is because, when you loop over with a for
loop, it only takes the keys as well:
>>> for k in obj:
... print k
...
1
3
5
7
>>>
But if you want to get the keys and the values, use .items()
:
>>> list(obj.items())
[(1, 2), (3, 4), (5, 6), (7, 8)]
>>>
Using a for
loop:
>>> for k, v in obj.items():
... print k, v
...
1 2
3 4
5 6
7 8
>>>
However, when you type in list.__doc__
, it gives you the same as [].__doc__
:
>>> print list.__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>>
>>> print [].__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>>
Kind of misleading :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With