python3 Need some clarity on dictionary and loops - python-3.x

the python newb here... I've spent WAY too long trying to make sense of this so perhaps somone colud give me some clarity. Here is the code, I'm unsure how line 7 works specifically.
dict = {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'four'}
letters = list(dict.keys())
print(letters)
for i in range(len(dict)):
print(dict[letters[i]]) #what is this line doing????!!!
I'm not sure how to read the syntax. I thought it was going into my letters list and puliing out 'a' 'b' 'c' 'd' yet I cannot print:
print(dict['a'])
how come I get error messages when trying to print this?

dict = {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'four'}
# convert the keys to a list = ['a', 'b', 'c', 'd']
letters = list(dict.keys())
print(letters)
# i is a number between 0 and the length of the dict, i.e. 4 (excluding 4)
for i in range(len(dict)):
# letters[i] = find the letter i-th letter from list `letters`, i.e. i=1 -> 'b'
# use that letter as the key and get its value, i.e. dict['b'] == 'two'
print(dict[letters[i]])
Notes:
As said in the comments, don't use a built-in name for variable names. Ideally, use a semantically clear name but for testing you'd often use 'd' for a dictionary, 'l' for a list and so on.
Your code now prints the values of the dict. I hope you are aware that you can do it much easier.
Like this:
for value in d.values():
print(value)

Related

increment a dictionary value by one in Python with querying hash table by one time, like map.merge in Java

For example, given list of str: ['a', 'b', 'a', 'a', 'b'], I want to get the counts of distinct string {'a' : 3, 'b' : 2}.
the naive method is like following:
lst = ['a', 'b', 'a', 'a', 'b']
counts = dict()
for w in lst:
counts[w] = counts.get(w, 0) + 1
However, it needs twice Hash Table queries. In fact, when we firstly called the get method, we have already known the bucket location. In principle, we can modify the bucket value in-place
without searching the bucket location twice. I know in Java we can use map.merge to get this optimization: https://stackoverflow.com/a/33711386/10969942
How to do it in Python?
This is no such method in Python. Whether visible or not, at least under the covers the table lookup will be done twice. But, as the answer you linked to said about Java, nobody much cares - hash table lookup is typically fast, and since you just looked up a key all the info to look it up again is likely sitting in L1 cache.
Two ways of spelling your task that are more idiomatic, but despite that the double-lookup isn't directly visible in either, it still occurs under covers:
>>> lst = ['a', 'b', 'a', 'a', 'b']
>>> from collections import defaultdict
>>> counts = defaultdict(int) # default value is int(); i.e., 0
>>> for w in lst:
... counts[w] += 1
>>> counts
defaultdict(<class 'int'>, {'a': 3, 'b': 2})
and
>>> from collections import Counter
>>> Counter(lst)
Counter({'a': 3, 'b': 2})

Why is: dict() reducing the length of the list when both list have same length?

I used dict(zip(list1, list2)) both list have a length of 211 but after dict(zip(list1,list2))
the length of the dictionary is 185. There is no duplicate value, why is there a drop in length and how to fix it so that the dict length is 211
I suggest that you should first amend your question to give more details (e.g. sample of the two lists, code used, etc.)
Nevertheless, the problem is quite obvious - you have duplicate keys in they key list, that is:
key_list = ['a', 'b', 'a'] #the duplicate key 'a'
value_list = [1, 2, 3]
d = dict(zip(key_list, value_list)) #d = {'a': 3, 'b': 2}

Fetching value from dataframe with certain condition

I have a dataframe which is containing 3 columns (['A','B','C]) and 3 rows in it.
We are using a for loop to fetch value(storing into variable) from above dataframe based upon certain condition from column B.
Further we are using list to store value present in variable.
Here question is upon checking list value, we are getting variable value, its type.
I'm not sure why it is happening. As list should contain only variable value only.
Please can anyone help us to get ideal solution for same.
Thanks,
Bhuwan
dataframe: columns-A,B,C rows value- a to i :df = ([a,b,c][d,b,f][g,b,i]).
list_1=[]
for i in range(0,9):
variable_1=df['A'][df.B == 'b']
list_1.append(variable_1)
print(list_1):
Ideal output: ['a','d','g']
while we are getting output as
['a type: object','d type: object','g type: object'].
You can get your ideal output like this:
import pandas as pd
df = pd.DataFrame({'A': ['a', 'd', 'g'], 'B': ['b', 'b', 'b'], 'C': ['c', 'f', 'i']})
list_1 = list(df[df['B'] == 'b']['A'].values) # <- this line
print(list_1)
> ['a', 'd', 'g']
You just need:
1) to filter your dataframe by column "B" df[df['B'] == 'b']
2) and only then take values of the resulted column "A", turning them into list

How to create a dictionary using the the list of letters as keys with values being the uppercase version of the letters

How to create a dictionary using the list of letters as keys with values being the uppercase version of the letters.
Using a dict comprehension with all of your chosen letters will give you key:value pairs with 'lower':'UPPER'.
lower_to_upper = {
letter: letter.upper()
for letter in 'abcdefghijklmnopqrstuvwxyz'
}
Use a list comprehension to build tuples that are input to create the dictionary.
mylist = ['a', 'b', 'c']
dict((i, i.upper()) for i in mylist)
output
{'a': 'A', 'b': 'B', 'c': 'C'}

How do I index an object in python?

I have a dictionary of objects,
e.g.
{'a': (one, two, three), 'b': (four, five, six)},
and i want to know how to pull out specific parts of each object in the dictionary so that i end up with a list of things that are in a certain position in each object.
For example ending up with; [two, five] (second position in each object)
How do you index the object so that this is possible?
You can't do this directly with an index operation, but the usual Pythonic approach is to use a list comprehension; e.g.
>>> D = {'a': ('one', 'two', 'three'), 'b': ('four', 'five', 'six')}
>>> [val[1] for val in D.values()]
['two', 'five']
Keep in mind that dictionaries are inherently unordered, so the order of the result is ambiguous in this case.
If you want a dictionary of the results, you can use a dictionary comprehension, e.g.
>>> {key:val[1] for key, val in D.items()}
{'a': 'two', 'b': 'five'}
For more information, you might check out the Python List Comprehension Docs.

Resources