简体   繁体   中英

When to use tuples in python

When are tuples appropriate to use?

I have a list of dictionaries (54 exactly), that look like this:

[{'1A': '1',
 '3E': '2',
 'PRODUCT NUMBER': '1',
 'Week': '1'}
  ,
 {'1A': '1',
  '1B': '1',
  '1C': '1',
  '1D': '2',
  '1E': '2',
  '2C': '1',
  '3E': '2',
  'PRODUCT NUMBER': '2'
  'Week' : '1'}...]

I need these dictionaries sorted by the product number, and im starting to think that a tuple may be a better data structure for this, rather than a dictionary?

You can sort them like this:

list_of_dicts=[{'1A': '1','3E': '2','PRODUCT NUMBER': '1','Week': '1'},
 {'1A': '1',
  '1B': '1',
  '1C': '1',
  '1D': '2',
  '1E': '2',
  '2C': '1',
  '3E': '2',
  'PRODUCT NUMBER': '2',
  'Week' : '1'}]


sorted_list_of_dicts = sorted(list_of_dicts, key=lambda x: x['PRODUCT NUMBER'])
print(sorted_list_of_dicts)

output:

[{'1A': '1', '3E': '2', 'PRODUCT NUMBER': '1', 'Week': '1'}, {'1A': '1', '1B': '1', '1C': '1', '1D': '2', '1E': '2', '2C': '1', '3E': '2', 'PRODUCT NUMBER': '2', 'Week': '1'}]

I think that using dicts is fine here.

The tuples are used when you need a fixed list and you don't have to change these values. example: weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") listOfSomeFruits = ("apple", "banana", "cherry", "apple", "cherry")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM