Python dictionary printing first word behaviour - python

I'm learning python and am on the topic of dictionaries. I wrote the following dictionary:
Team={
('projectmanager','Asma'): 'Sara',
('ba','Richard'): 'Steve',
('tester','Asma'): 'Rob',
'developer1': 'Misbah',
'developer2': 'Mariam'
}
I then wrote the following code:
for k,v in Team.items():
profile=type(k)
print('engTeam => {1} {0}'.format(k[0][0],profile))
The output I get is:
Team => <class 'str'> e
Team => <class 'str'> d
Team => <class 'tuple'> i
Team => <class 'str'> m
Team => <class 'tuple'> b
Team => <class 'str'> s
Team => <class 'tuple'> p
Team => <class 'str'> e
Team => <class 'str'> a
I don't understand why the first character of all non-tuple entries are being printed. If I think about it k[0][0] in my mind means get me the first element of the dictionary then the first sub element. But the non-tuple words don't have a sub element so the output should be blank, shouldn't it? Also k[0][0] should be printing the whole first word in the tuple e.g. 'projectmanager' instead of the first character of the first tuple word. What am I missing in understanding what k[0][0] means and what it is doing?

If I think about it k[0][0] in my mind means get me the first element of the dictionary then the first sub element.
No, k is the key of a given key-value pair. You are iterating over the items, which are those pairs:
for k,v in Team.items():
Each key-value pair is assigned to the names k and v there.
Given that you have two different types of keys in your dictionary, strings and tuples, your type() information shows you exactly that; you print a series of <class 'str'> and <class 'type'> for those keys.
So if k is a tuple, then k[0] is the first element in that tuple and k[0][0] is the first character of that first element:
>>> k = ('projectmanager', 'Asma')
>>> type(k)
<class 'tuple'>
>>> k[0]
'projectmanager'
>>> k[0][0]
'p'
For strings, k[0] would be the first character. But a single character is a string too. A string of length 1, so getting the first element of that string is still a string, again of length 1:
>>> k = 'developer1'
>>> type(k)
<class 'str'>
>>> k[0]
'd'
>>> type(k[0])
<class 'str'>
>>> len(k[0])
1
>>> k[0][0]
'd'
You wouldn't get an empty value here.

Consider,
First case- key, k is set to be a to be tuple. For instance ('projectmanager','Asma'). Hence obviously k[0][0] will print out p
Second case (the more tricky one) when k is set to be a string, k[0] is the first element of string. k[0] is hence a string of length 1. Doing
k[0][0] would access the first element of k[0] which is inturn the same as k[0] is a string of length 1.For example when k is 'developer1' ,k[0] is'd' and k[0][0] is hence 'd'
Hope this helps, good luck

Related

How to strip a tuple which is in a Python list

my_list = [(101)]
Output: my_list = [101]
If number of elements are more than 1 in my_list then i can run for loop and can strip the tuple from the list , but when number of element is one, then for loop also gives an error .Error :int object is not iterable.
Because single int surrounded by () has type int.
>>> t = (1)
>>> type(t)
<class 'int'>
You can use , to make it tuple. (if it has only one value.)
>>> t = (1,)
>>> type(t)
<class 'tuple'>
Assuming the first element of list is tuple.
my_list = [(101)]
if isinstance(my_list[0], tuple):
my_list = [i for i in my_list[0]]
print(my_list)
In case of single element, my_list will evaluate to what you expect

output for str.join() method is not consistent

Lets assign two variables:
>>> a_id = 'c99faf24275d476d84e0c8f0ad953582'
>>> u_id = '59958a11a6ad4d8b39707a70'
Right output:
>>> a_id+u_id
'c99faf24275d476d84e0c8f0ad95358259958a11a6ad4d8b39707a70'
Wrong output:
>>> str.join(a_id,u_id)
'5c99faf24275d476d84e0c8f0ad9535829c99faf24275d476d84e0c8f0ad9535829c99faf24275d476d84e0c8f0ad9535825c99faf24275d476d84e0c8f0ad9535828c99faf24275d476d84e0c8f0ad953582ac99faf24275d476d84e0c8f0ad9535821c99faf24275d476d84e0c8f0ad9535821c99faf24275d476d84e0c8f0ad953582ac99faf24275d476d84e0c8f0ad9535826c99faf24275d476d84e0c8f0ad953582ac99faf24275d476d84e0c8f0ad953582dc99faf24275d476d84e0c8f0ad9535824c99faf24275d476d84e0c8f0ad953582dc99faf24275d476d84e0c8f0ad9535828c99faf24275d476d84e0c8f0ad953582bc99faf24275d476d84e0c8f0ad9535823c99faf24275d476d84e0c8f0ad9535829c99faf24275d476d84e0c8f0ad9535827c99faf24275d476d84e0c8f0ad9535820c99faf24275d476d84e0c8f0ad9535827c99faf24275d476d84e0c8f0ad953582ac99faf24275d476d84e0c8f0ad9535827c99faf24275d476d84e0c8f0ad9535820'
Now consider this case, the output is correct now:
>>> a="asdf"
>>> b="asdfsdfsd"
>>> str.join(a,b)
'aasdfsasdfdasdffasdfsasdfdasdffasdfsasdfd'
Confirming the type of all variables in the example:
>>> type(a)
<class 'str'>
>>> type(a_id)
<class 'str'>
>>> type(u_id)
<class 'str'>
Edit
I just realized the second case in the output was not quite what I expected as well. I was using join method in a wrong way.
str.join(a, b) is equivalent to a.join(b), provided a is a str object and b is an iterable. Strings are always iterable, as you will be iterating though each characters in it when you're iterating over a string.
This is basically "insert a copy of a between every element of b (as an iterable)", so if a and b are both strings, a copy of a is inserted into every pair of letters in b. For example:
>>> str.join(".", "123456")
'1.2.3.4.5.6'
If you simply want to concatenate two strings, + is enough, not join:
>>> "." + "123456"
'.123456'
If you really want join, put the strings in a list and use an empty string as "delimiter":
>>> str.join('', ['123', '456', '7890'])
'1234567890'
>>> ''.join(['123', '456', '7890'])
'1234567890'

How to index into the string result of a dictionary item reference?

What is the best syntax to reference the characters in a reference to dictionary item? How do I make it indexable?
>>> myd = {'abc':'123','def':'456','ghi':'789'}
>>> myd
{'def': '456', 'ghi': '789', 'abc': '123'}
>>> type(myd)
<class 'dict'>
>>> s=myd['def']
>>> s
'456'
>>> type(s)
<class 'str'>
>>> s[0]
'4'
>>> s[2]
'6'
>>> myd['def'].[0]
SyntaxError: invalid syntax
myd['def'] returns you the string '456'. You can access a specific index of an array using the same bracket notation that most languages support. Hence, myd['def'][0] will return the string literal '4'
Just remove the . and it will work.
You have not actually sliced your string. Once you get the value myd['def'] it returns a string. You then need to use [] to slice it. [0] in this case however adding a . is just a syntax error in Python.
This link describes slicing strings

In Python, what are the data type if appending an integer to a list of strings

This is what I do:
>>> arr1 = ['er','t','ty'] # I suppose these three elements are strings
>>> arr1.append(3) # try to append an integer 3
>>> print arr1
['er', 't', 'ty', 3]
Question: I think that arr1 is an list; 'er','t','ty' are strings; and 3 is still an integer. Is this correct? Or 3 has been automatically casted as string.
list is a sequence of heterogeneous objects. They can be any type. You can verify this with the built-in function type():
>>> arr1 = ['er','t','ty']
>>> arr1.append(3)
>>> print(arr1)
['er', 't', 'ty', 3]
>>> for object in arr1:
... print(object, type(object))
...
er <class 'str'>
t <class 'str'>
ty <class 'str'>
3 <class 'int'>
3 is still an integer.
list can contain different type of items.
itself has type as <class 'list'>
Unlike other languages like C++, there is not things like "integer list" or "foo list", it is just a list in python.

How to properly convert list of one element to a tuple with one element

>>> list=['Hello']
>>> tuple(list)
('Hello',)
Why is the result of the above statements ('Hello',) and not ('Hello')?. I would have expected it to be the later.
You've got it right. In python if you do:
a = ("hello")
a will be a string since the parenthesis in this context are used for grouping things together. It is actually the comma which makes a tuple, not the parenthesis (parenthesis are just needed to avoid ambiguity in certain situations like function calls)...
a = "Hello","goodbye" #Look Ma! No Parenthesis!
print (type(a)) #<type 'tuple'>
a = ("Hello")
print (type(a)) #<type 'str'>
a = ("Hello",)
print (type(a)) #<type 'tuple'>
a = "Hello",
print (type(a)) #<type 'tuple'>
And finally (and most direct for your question):
>>> a = ['Hello']
>>> b = tuple(a)
>>> print (type(b)) #<type 'tuple'> -- It thinks it is a tuple
>>> print (b[0]) #'Hello' -- It acts like a tuple too -- Must be :)

Categories