R's list() allow labelled elements as well, is there an equivalent way in Python to achieve the following?
list("prob", "topTalent", name="Roger")
The Python documentation at https://docs.python.org/3/tutorial/introduction.html implies that you can create recursive structures (the proper R term for structures that can have a tree-characteristic) of varying types with the "[" operator:
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
I'm just an R guy but that would seem to imply that Python's "list" data-type strongly resembles R's list type.
To get named "recursive" structures, it appears one needs to use a "dictionary" ( created with flanking "{","}" ).
>>> x = {'a':a, 'n':n}
>>> x
{'a': ['a', 'b', 'c'], 'n': [1, 2, 3]}
It appears that Python requires names for its dictionary entries while R allows both named and unnamed entries in a list.
>>> x = {'a':a, 'n':n, 'z':[1,2,3], 'zz':{'s':[4,5,6], 'd':['t','y']} }
>>> x
{'a': ['a', 'b', 'c'], 'n': [1, 2, 3], 'z': [1, 2, 3], 'zz': {'s': [4, 5, 6], 'd': ['t', 'y']}}
The accession from Python dicts resembles the access to items when using R:
>>> x['zz']
{'s': [4, 5, 6], 'd': ['t', 'y']}
>>> x['zz']['s']
[4, 5, 6]
There's no equivalent. Python lists have nothing like R's names
, and OrderedDict (as suggested in the comments) does not allow the equivalent of unnamed elements or duplicate names, as well as not supporting access by element position.
A dict would be the most common way of associating objects with names in Python, but it's still very different from an R list with names. You could certainly create your own class attempting to mimic the equivalent R data structure, perhaps subclassing list
or collections.UserList
, but you'd have to implement a lot of functionality yourself, and existing functions you pass your object to wouldn't know what to do with the names.
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