Python Forum
Looping through a dictionary for every other value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping through a dictionary for every other value
#5
Complete text of challenge:

1) Start with this list: ['a', 'b', 'c', ..., 'z'}
And create a function that turns it into this dictionary: {1: 'a', 2: 'b', 3: 'c', ..., 26: 'z'}

2) Start with this string: 'abc...z'
And create a function that turns it into this dictionary: {1: 'a', 2: 'b', 3: 'c', ..., 26: 'z'}

3) Take one of the above functions and include only the odd numbers / letters: {1: 'a', 3: 'c', ..., 25: 'y'}

Complete code for part 1 & 2 (part 3 is what i am trying to solve).

#Create list of letters
import string
letlist = list(string.ascii_lowercase)

#Create string of letters
letstring = string.ascii_lowercase

#Create list of numbers
list1=[]
for i in range (1, 27):
    list1.append(i)

#Create dictionary for part 1
def dictfunc():
    zipped =dict(zip(list1,letlist))

dictfunc()

#Create dictionary for part 2
def dictfun2():
    zipped2 = dict(zip(list1, letstring))

dictfun2()
If I don't use global I get an error about the dictionary not being found. My guess is somehow it is local in scope to the function that is why i tried using global.

Really appreciate all the help.

Adding this snippet

odd_entries = {k:v for k,v in zipped.items() if v % 2}
print (odd_entries)
Returns an error I've never seen before (good chance I screwed up something in the code above because some of it I didnt understand specically the k:v part.)

Traceback (most recent call last):
File "C:/Users/c0unt3rpl4y/PycharmProjects/House/scratchpad.py", line 21, in <module>
odd_entries = {k:v for k,v in zipped.items() if v % 2}
File "C:/Users/c0unt3rpl4y/PycharmProjects/House/scratchpad.py", line 21, in <dictcomp>
odd_entries = {k:v for k,v in zipped.items() if v % 2}
TypeError: not all arguments converted during string formatting
Reply


Messages In This Thread
RE: Looping through a dictionary for every other value - by fad3r - Jan-25-2018, 04:03 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Looping to Create Nested Dictionary gngu2691 10 33,676 Jun-22-2018, 04:11 PM
Last Post: anickone

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020