[Tutor] python questions about dictionary loops

Steven D'Aprano steve at pearwood.info
Wed Feb 29 00:25:45 CET 2012


justin fargus wrote:
> Hello,
> 
> 
> I'm new to Python. Just started a few weeks ago and I've been learning some
> basic things that I would like to put together but I don't even know where
> to began. I am trying to do the following:
> 
> Make a program using two sentences of about 8 words (total between the two
> sentences).  I would then like to create a dictionary {} and split the
> words of each sentence using one sentence as a dictionary key and using the
> other sentence for the dictionary value.  I would then like to use a loop
> (while or for) that will write out a file that has the dictionary key and
> dictionary value to it.  How can I go about doing this?

You don't tell us what parts of the problem are causing you trouble. Also, I 
don't know if this is homework or not, but a dictionary does not sound like 
the right data structure to use here. What happens if the first sentence (the 
keys) contains duplicate words?


Here are some examples to get you started. Run them in Python, and see what 
they do. They won't solve your problem exactly, but if you study them and see 
what they are doing, you should be able to adapt them to solve your problem. 
If anything is unclear, please ask.


paragraph = "This line has one sentence.\nAnd so does this one."
first_line, second_line = paragraph.split('\n')
print(first_line)
print(second_line)

sentence = "this is a sentence of seven words"
words = sentence.split()
ordinals = "1st 2nd 3rd 4th 5th 6th 7th".split()
for ordinal, word in zip(ordinals, words):
     print("%s ::  %s" % (ordinal, word))

d = {}
for key, value in zip(['a', 'bb', 'ccc', 'dddd'], [1, 2, 3, 4]):
     d[key] = value

for k, v in d.items():
     print("%s ::  %s" % (k, v))



Do you need any of this code explained, or is it clear what it does?


-- 
Steven



More information about the Tutor mailing list