What is a Collection?

damjaeng-i·2022년 8월 17일
0

2022 PY4E

목록 보기
15/18
post-thumbnail

What is a Collection?

  • A collection is nice because we can put more than one value in it and carry them all around in one convenient package
  • We have a bunch of values in a single “variable”
  • We do this by having more than one place “in” the variable
  • We have ways of finding the different places in the variable

What is not a “Collection”?

  • Most of our variables have one value in them - when we put a new value in the variable - the old value is overwritten
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4

A Story of Two Collections..

  • List
    • A linear collection of values that stay in order
  • Dictionary
    • A “bag” of values, each with its own label

Dictionaries

  • Dictionaries are Python’s most powerful data collection
  • Dictionaries allow us to do fast database-like operations in Python
  • Dictionaries have different names in different languages
    • Associative Arrays - Perl / PHP
    • Properties or Map or HashMap - Java
    • Property Bag - C# / .Net
  • Lists index their entries based on the position in the list
  • Dictionaries are like bags - no order
  • So we index the things we put in the dictionary with a “lookup tag”
>>> purse = dict()
>>> purse['money'] = 12
>>> purse['candy'] = 3
>>> purse['tissues'] = 75
>>> print(purse)
('money': 12, 'tissues': 75, 'candy': 3)
>>> print(purse['candy'])
3
>>> purse['candy'] = purse['candy'] +2
>>> print(purse)
('money': 12, 'tissues': 75, 'candy': 5) 

Comparing Lists and Dictionaries

Dictionaries are like lists except that they use keys instead of numbers to look up values

>>> 1st = list()
>>> 1st.append(21)
>>> 1st.append(183)
>>> print(1st)
[21, 183]
>>> 1st[0] = 23
>>> print(1st)
[23, 183]

Dictionary Lieterals (Constants)

  • Dictionary literals use curly braces and have a list of key: value pairs
  • You can make an empty dictionary using empty curly braces
python
>>> jjj = {'chuck' : 1, 'fred' : 42, 'jan': 100}
>>> print(jjj)
{'jan': 100, 'chuck': 1, 'fred': 42}
>>> ooo = { }
>>> print(ooo)
{}
>>> 
profile
목표 : 부지런한 개발자

0개의 댓글