Skip to content

[Python] Tutorial(11) Tuples, Sets, Dictionary

Last Updated on 2021-04-10 by Clay

Python has many kinds of data types, so it's hard to me to give examples of all of them.

So, I introduce the data type we use in Python by simple today.

"Tuple", as similar as List. We can store the different data type value in them. But tuple we can't add, remove, update our value in tuple.

Set also as similar as List. But set have no two value on same.

Dictionary is a very useful data type, we call it "dict" in Python. The data store way is like key-value, one key correspond one value. We can store the useful information and analyze it.


Tuple

First, we introduce the data type "tuple"!

a = (1, 2, 2, 3, 3, 3, 'a', 'b', 'c', 'c')
print(a.count(2))
print(a.count(3))
print(a.index(1))
print(a.index('a'))


The variable "a" is a way we store the data in tuple. And following above, we can't update the value of it.

a.count(n) can count how many elements n we have.
a.index(n) can display the position element "n" appear, it's meaning the index of n in tuple.

Output:

2
3
0
6

2: we can see 2 in tuple twice.
3: we can see 3 in tuple tree times.
0: index of 1 in tuple. 1 is the first value in tuple, so index is 0.
6: it is the value of a, you can check the real index value.


Set

Explaining data type "set", I'm very guilty. Haha.

Before this tutorial, I never use this data type clearly. I used it always want to remove the value in list there are repeat. (It's very useful!)

a = set(a)
b = set([1, 3, 5, 'a', 'c', 'e'])

print(a)
print(b)


Output:

{'c', 1, 2, 3, 'b', 'a'}
{1, 3, 5, 'a', 'e', 'c'}

Forgiving my lazy. I convert the data type tuple of the above to data type set.

And you can see, the repeat values are all removed.

If you print these data, you may see some different data type.

And then, we introduce more function in set!

c = a.copy()
print(c)


The instruction copy is also in List, and their feature are on same. They also can give their value for an other variable, here is copying values for variable c.

It should be noted: if you don't use the copy command, it will let two variables they share a same memory addressing! This will cause us modify one of them, the other will follow the changing.

As far as I know, many Bugs in Python because it.

c = a.copy()
print(c)

c.clear()
print(c)


Output:

{1, 2, 3, 'b', 'a', 'c'}
set()

First we can see, the first variable from a.copy(), we print it and it have all value in a.
And second, we execute the command clear() to c, it will clear all value in c! It will be the following we show, the set have no any value! everyone be careful, don't remove the data we want to use.

The set data can be like the set taught in "Linear Algebra". For simple calculations of "Intersection", "Union", "Difference"......

print(a)
print(b)
print('Intersection:', a.intersection(b))
print('Union:', a.union(b))
print('Difference:', a.difference(b))


Output:

{'c', 1, 2, 3, 'b', 'a'}
{1, 3, 5, 'a', 'e', 'c'}
Intersection: : {'c', 1, 3, 'a'}
Union : {'c', 1, 2, 3, 5, 'e', 'b', 'a'}
Difference : {'b', 2}

We can see that the above instructions can really calculate these features!

And it is worth mentioning that the addition and deletion of set. It can be done simply by using add() and remove().

c.clear()
c.add(1)
c.add(2)
{1, 2}
c.remove(1)
print()
print(c)


Output:

{1, 2}
{2}

We can see: add() can be used to add elements to set, and remove() can be used to remove elements from set.


Dictionary

Finally, we come to the part to introduce "dictionary"! But I think its meaning is in "doing it", I can't teach the core of it in fact!

But please let me talk a little bit here. The dictionary can be used for statistics (although this does not seem to be its main function, after all, Python actually has bulit-in collections, this package can do "statistics").

And then, if you combined with Json's data storage format, your information will be vary well to managed!

My explanation is that there is no way to make people understand, of course. My mistake.

The usefulness of the dictionary is handed over to those who are fortunate enough to read this article to study slowly.

Below I will explain how to use the dict data type in Python and how to manipulate the data stored in this data type.

Basically, the assignment of dict can be divided into two types: the first is to directly give the

a = dict({1: 2, 2:4, 3:6})
print(a[1])
print(a[2])
print(a[3])


Output:

2
4
6

We set a data type dictionary, and we give it a key-value format.

And here we can see, the key is a number, and its value is its double.

We can try set a variable and give it for data type dictionary.

b = dict()

b[1] = 2
b[2] = 4
b[3] = 6

print(b[1])
print(b[2])
print(b[3])


Output:

2
4
6

b[n] = m is giving the key-value.

Data type dict also has clear(), copy() ...... you can refer the above in the "set" chapter.

print(a.items())
print(a.keys())
print(a.values())


Output:

dict_items([(1, 2), (2, 4), (3, 6)])
dict_keys([1, 2, 3])
dict_values([2, 4, 6])

Except printing the dictionary to check our data, we can use items(), keys(), values() to check our data.

items(): print key-value
keys(): print dictionary key
values(): print dictionary value


Statistic

And then, let me show you how to statistic by data type dictionary!

text = 'This is a very big and red apple.'
statistic = {}

for word in text:
    statistic[word] = statistic.get(word,0) + 1

for key in statistic:
    print(key, statistic[key])


Output:

T 1
h 1
i 3
s 2
  7
a 3
v 1
e 3
r 2
y 1
b 1
g 1
n 1
d 2
p 2
l 1
. 1

First, we set a text we want to statistic.
And then, we declare the variable to data type dict, now is null.

Use for-loop to check every letter in our text, and we use the function get() to statistic.

get(n, m) is a way to check data type dict. You can return the value of dict where key is n; If there is no key value of n in key, then we return m we set. (The default is None)

So we can count the number of letters: if the letter is already in the dictionary, we will return its current quantity and then +1; if the current letter has not been counted, then we initialize the key to 0; then + 1.

Finally, we also use for-loop to iterate over the entire dict and print out the key and value.

Is it very clever?

Oh yeah, by the way, everyone should see the key-value have no sorted. Maybe you can think about it: How do you sort these values?

You can challenge!


References


Read More

2 thoughts on “[Python] Tutorial(11) Tuples, Sets, Dictionary”

Leave a ReplyCancel reply

Exit mobile version