python - What is the major difference between list of tuples and a dictionary? -
for example:
a = (1,2,3) b= (5,6,7) c=zip(a,b) [(1,5),(2,6),(3,7)]
a dictionary have {1:5, 2:6, 3:7}
a list of pairs not fundamental data structure. may choose use if want, it's making list of lists, or list of dicts. list data structure meant store linear data: data make sense write out on number line, labeling each piece of data 0,1,2,3,...
a dictionary hash table, built o(1) lookup time. dictionary known 'map' data structure, because implements mapping (like function), a
goes 1
, b
goes 2
, , dictionaries have implies direction (in case, abc->123, not 123->abc). hash table has no concept of index.
to compare:
mydictionary = {'a':1, 'b':2, 'c':3} mydictionary['a'] input:a,b,or c output:1,2,or 3 e.g. "what 'a' map to?" 'a' | \ \---> [speedy hash table] below | | math extracts data | ____________________ / \ { a:1 } { b:2 c:3 } \____________________/ nebulous magic cloud | \ \-----> 1
now list:
mylist = ['a', 'b', 'c'] in memory: ['a', 'b', 'c'] 0 1 2 <-- indices >>> mylist[1] 'b'
(sidenote: show above array, contiguous in memory... list may not contiguous in memory (and not), 'act' is, e.g. takes o(1) time element index (this not same dictionary index, 'a','b','c' in our example; list indices 0,1,2,3,4,... nomatter data you're storing). elaborate, can instantly third item in list, or second-to-last item, or middle item.)
a list of pairs normal list... of pairs:
[('a',1), ('b',2), ('c',3)] in memory: [ pair0 , pair1 , pair2 ] 0 1 2 elsewhere in memory: pair0 --> ('a',1) elsewhere in memory: pair1 --> ('b',2) pair2 --> ('c',3)
finding in list take time proportional how many items in list. finding needle in haystack; have examine every single piece of hay find needle. use lists linear ordered data, graphs of temperature each element in list unit of time, or holding email messages in order.
to answer question may trying ask, "when use list of pairs or dictionary if having trouble deciding between two?", soft fuzzy rule want use list of pairs when either
- you care order of data (e.g. want pair comes before or after pair), or
- your data cannot held in dictionary, e.g. have duplicate values, like
{'a':1, 'a':2, 'b':3, 'c':4} #this make no sense put in dictionary mydict = {} mydict['a'] = 1 mydict['a'] = 2 #overwrites previous mapping! mydict['b'] = 3 mydict['c'] = 4 >>> mydict {'a':2, 'b':3, 'c':4}
there may times when need data structure not list or dictionary, such tree. sometimes, may want use both list , dictionary.
Comments
Post a Comment