Python iterating and dictionary - python

I'm trying to create a dictionary with keys that are every 3 items of the list such as..(a,b,c) then (b,c,d) then (c,d,e) and the value of each key is the direct next letter, so the value for (a,b,c) would be d and the value for (b,c,d) would be e. This is the code I have so far but the problem is when i becomes 2, the dict tries to append L(2+3) which result in an index error. Also..if num is = 4 instead of 3, then my code wouldn't work. Can I get some hints as to what I should do to fix these 2 problems. Thank you
L = ['a','b','c','d','e']
num = 3
for i in range(len(L)-2):
a_dict[tuple(L[i:i+num])].append(L[i+num])

You can do it in one line like this:
import string
letters = string.ascii_lowercase
num = 3
mydict = {tuple(letters[i:i+num]):letters[i+num] for i in range(len(letters)-num)}
Here string.ascii_lowercase is a string containing English alphabet in lowercase. You can treat it same way as a list (slicing, element selection).

You are supposed to use "=" not ".append()" to add to dictionaries, i.e.
dictionary[key] = value
Also, you can use a modulus (%) to make sure that the list indexes do not get above the length of the list.
This slightly modified code works, including when num = 4 or num = 2 :
L = ['a','b','c','d','e']
num = 3
a_dict = {}
for i in range(len(L) - num):
a_dict[tuple(L[i:(i+num)%len(L)])] = (L[(i+num)%len(L)])
I hope that this is helpful for you.

Related

Populating a List - Python assigns index and gives error

I have a solution to count the number of occurrences of each letter in a string and return a dict.
def count_characters(in_str):
all_freq = {}
for i in in_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
return all_freq
count_characters("Hello")
It works.
I am trying to understand how Python automatically assigns each letter as the key to the dict - its not explicitly assigned. I replace the null dictionary assignment with a list and expect to get just the frequency, without the letter.
def count_characters(in_str):
all_freq = []
for i in in_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
return all_freq
count_characters("Hello")
I get an error.
TypeError: list indices must be integers or slices, not str
My question is:
How does each letter get automatically assigned as the key?
How can I return just the numbers as a list - without the letter?
How does each letter get automatically assigned as the key?
You are doing it explicitly in all_freq[i] = 1. Here, i contains a letter (though I think the variable could be named better — i typically stands for an idex of some sort, which this isn't).
How can I return just the numbers as a list - without the letter?
You could still build a dictionary and then return list(all_freq.values()). Though, if you do that, how would you know which letter each count corresponds to?
This is probably not relevant for your exercise, but the standard library already has a class for doing this sort of counting: collections.Counter.
List are indexing with integer, in your second exemple you use dictionary synthax with a list, that why python complain.
You can use count method
def count_characters(in_str):
all_freq = []
for i in in_str:
all_freq.append(in_str.count(i))
return all_freq
count_characters("Hello")
Edit : I agree with #NPE comment
You could still build a dictionary and then return list(all_freq.values()). Though, if you do that, how would you know which letter each count corresponds to?
This is probably not relevant for your exercise, but the standard library already has a class for doing this sort of counting: collections.Counter.
It's simple when we use built-in methods of dictionary like .keys(), .values()
Example:
def count_char(string):
dict = {}
count = 0
for i in string :
if i in dict.keys():
dict[i] +=1
else:
dict[i] = 1
for j in dict.values():
count += j
print(dict)
print(count)

How to fix 'int object is not iterable'

I'm trying to add all the integers in the 'a' variable, but this 'a' variable isn't working as a list nor a string, despite having various different integers in it.
I'm writing a Python program that given a positive integer num, provided by the user, prints the sum of all its divisors.
I've already tried to make this 'a' variable a list but the same error happens
import math
num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a)
for i in (b):
x = num / i
if math.floor(x) == x:
c = list(i)
I've already tried to make this 'a' variable a list but the same error happens: 'int object is not iterable'
list() creates a new list, and its argument must be an iterable (e.g. a tuple, another list, etc.). If you only pass one number, i, it won't work.
I suppose what you want to do is not to create a new list with each loop iteration, but add the i element to an already existing list.
You can achieve it this way:
num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a)
divisors = [] # create a new list where the results will be stored
for i in (b):
x = num / i
if math.floor(x) == x:
divisors.append(i) # add the number at the end of the list
If you want to sum all the divisors, use:
sum(divisors)
An even more 'Pythonic' (though, admittedly, not necessarily easier to read if you're not used to list comprehensions) way to achieve the same result would be:
num = int(input("Num: "))
divisors_sum = sum(i for i in range(1, num + 1) if num//i == num/i)
I assume you're using Python 3 here. In Python 3, // is floor division, so you don't have to use math.floor. See this post for more details on // vs. /.
You can create an empty list outside of the loop: c = [], and then each time append an element to the list by c.append(i).

I just want to print the key, not their index

I need to print the keys + their values and it always prints the index of the key too, how can I fix that?
def task_3_4(something:str):
alphabet =list(string.ascii_letters)
i = 0
k=0
while i < len(alphabet):
dicts = {alphabet[i]: 0}
count = something.count(alphabet[i])
dicts[i] = count
if 0 < count:
for k in dicts:
print(k)
i = i+1
Based on the code it seems like you are trying to do some sort of counter of different characters in the string?
There is no index. your "index" is the "i" iterator you are using for your while loop. This simply makes a new key in dicts as called by dicts[i]. Thus when you call the print loop, it just iterates through and reads out I as well.
Try:
dicts[alphabet[i]] = count
Also your print function only prints out the key of the dict entry instead of the key-value pair. to do that you can try:
for k in dicts:
print(k,dicts[k])
Try reading up on the python docs for dicts.
https://docs.python.org/3/tutorial/datastructures.html

Why is this list comprehension for appending digits from input not working?

Hi new to Python and trying to learn using comprehensions.
Developed below code to read numbers in a string and extract the numbers however trying to replace with a single comprehension statement. Please advise
sent = input('Enter a string')
digit = []
for i in range(len(sent)):
if sent[i].isdigit():
d = sent[i]
digit.append(d)
Tried below method
digit = [d for i in range(len(sent)) if sent[i].isdigit() = d]
You are close; this is one way:
sent = input('Enter a string')
# 123
digit = [int(sent[i]) for i in range(len(sent)) if sent[i].isdigit()]
print(digit)
# [1, 2, 3]
A more Pythonic approach is to iterate values directly:
digit = [int(i) for i in sent if i.isdigit()]
The problem with your code is d is undefined in your list comprehension.

how to modify a list that is a value in a dictionary?

If I have a dictionary like so:
d = {'USA' : [0,0,0], 'CAN' : [0,0,0]}
How can I update a specific element in the value?
My goal is to update it to look like (for example) this:
d = {'USA' : [0,1,0], 'CAN' : [1,0,0]}
I was thinking something like
d['USA'] = d.get('USA')[1] + 1
d['CAN'] = d.get('CAN')[0] + 1
but this doesn't seem to work.
Any suggestions?
I hope this is clear.
You have lists inside of your dictionary, so the d[key] part of the expression returns a list. Just keep adding [..] indexings:
d['USA'][1] += 1
d['CAN'][0] += 1
You could break it down with intermediary variables if that is easier:
sublist = d['USA']
sublist[1] += 1
sublist = d['CAN']
sublist[0] += 1
The simplest way would be to just say
d['USA'][1] += 1
That will get you the updated list.
Do
d['USA'][1]=d['USA'][1]+1
d['CAN'][0]=d['USA'][0]+1
In your example you were replacing the whole list with a single number.

Categories

Resources