Given:
>>> di1={'a':1,'b':2, 'c':3}
If I do:
>>> dir(di1.items())
['__and__', '__class__', '__contains__', '__delattr__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__ne__', '__new__', '__or__', '__rand__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__ror__',
'__rsub__', '__rxor__', '__setattr__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__',
'__xor__', 'isdisjoint']
There are some interesting methods there.
Try __ror__
:
>>> help(di1.items())
...
| __ror__(self, value, /)
| Return value|self.
...
Where value
is only an iterable according to Python errors.
Let's try some examples:
>>> di1.items().__ror__([1])
{('c', 3), 1, ('b', 2), ('a', 1)}
>>> di1.items().__ror__([10])
{('c', 3), ('b', 2), 10, ('a', 1)}
>>> di1.items().__ror__([1000])
{1000, ('b', 2), ('c', 3), ('a', 1)}
>>> di1.items().__ror__([10,1000])
{('c', 3), ('a', 1), 1000, 10, ('b', 2)}
Headscratch
What are the use-cases for a binary or
of an dict view with an interable? (or the other binary methods there, __rxor__
, __rand__
also...)
After scratching a bit harder, I found that what I was looking at is one element of the dict view set operations that include set operations on .items()
.
Given:
>>> di1={'a': 1, 'b': 2, 'c': 3}
>>> di2={'a': 1, 'b': 3, 'c': 4, 'd':47, 'e':0}
Examples:
>>> di1.items() & di2.items()
{('a', 1)}
# Only 'a' because with .items both key and value must be the same
# equivalent to:
# set(di1.items()) & set(di2.items())
# However: values must be hashable
>>> di1.keys() & ['a','d']
{'a'}
# only keys compared to a list
# equivalent to set(di1.keys()) & set(['a', 'd'])
# carefule tho:
# (di1.keys() | di2.keys()) & set(['a', 'e']) is right
# di1.keys() | di2.keys() & set(['a', 'e']) is WRONG
# since & is higher precedence than |
>>> di1.keys() & 'zycd'
{'c'}
# and string
# equivalent to set(di1.keys()) & set('zycd')
>>> di1.keys() | di2.keys()
{'b', 'a', 'd', 'e', 'c'}
# all the keys in both dicts -- since sets are used, not
# necessarily in order
>>> di2.keys() - di1.keys()
{'d', 'e'}
# keys exclusively in di2
That is useful!
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