Python @ DjangoSpin

Python: Interchanging Data Structures

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Interchanging Data Structures in Python

Interchanging Data Structures in Python

You can make any data structure from any other data structure using the builtin constructors list(), tuple(), dict(), set(), frozenset() of their respective classes. This interchanging operation is incredibly helpful in certain situations e.g. while reversing a tuple, while removing duplicates from a list, extracting keys and values from a dictionary, making a set immutable by initializing a frozenset from it etc. Examples:

# list to tuple
# transforming a mutable list into an immutable tuple
>>> myList = [number for number in range(1, 11)]
>>> myTuple = tuple( myList )
>>> print("Type: ", type( myTuple ), ";", "Contents: ", myTuple)
Type:  <class 'tuple'> ; Contents:  (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
 
# tuple to list
# sorting a tuple
>>> tupleOfNumbers = (5, 4, 2, 3, 1)
>>> listOfNumbers = list(tupleOfNumbers)       
>>> listOfNumbers.sort()
>>> listOfNumbers
[1, 2, 3, 4, 5]
>>> newTupleOfNumbers = tuple(listOfNumbers)  
>>> newTupleOfNumbers
(1, 2, 3, 4, 5)
 
 
# list to set
# removing duplicates
>>> myList = [number for number in range(1, 11)]
>>> myList2 = [number for number in range(5, 16)]
>>> myList + myList2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> mySet = set( myList + myList2 )
>>> mySet
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
 
# set to frozenset
# making a set immutable
>>> mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
>>> mySet.add(16)
>>> mySet
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
>>> myImmutableSet = frozenset( mySet )
>>> myImmutableSet.add(17)
# Traceback information
AttributeError: 'frozenset' object has no attribute 'add'
 
# dict to list
# initializing a new dictionary from the keys of an exisitng dictionary
>>> myDictionary = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> myListOfKeys = list( myDictionary.keys() )
>>> myListOfKeys
['one', 'four', 'five', 'three', 'two']
>>> myNewDictionary = dict.fromkeys( myListOfKeys )
>>> myNewDictionary
{'one': None, 'four': None, 'two': None, 'three': None, 'five': None}


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply