wonder
wonder

Reputation: 3

iterating through multiple values [for the same key] of an ordered dictionary python

I have an ordered dictionary with multiple values for the same key. I need to iterate through the items and perform different operations on each of the values.

the dict is as below :

OrderedDict([('1', ['file a','file1','file2','file3', 'Substringb']), ('2', ['file c', 'Substringd']), ('3', ['filed', 'Substringe']),('4', ['file f', 'Substringg']), ('5', ['file h', 'Substringi'])]

Each item will have file paths and a substring. I do not have control over how many files I would receive from the other function. I would want to open up each of them and look for the substring. Right now I am getting a too many values to unpack when I do below:

Below is the code that I use: When I extract the values and try to iterate through each_file, it is not working - print each would print just the first character of the filepath[ex: 'C' when the filepath is "'C:\Users\xxxxxx\Documents\something.txt" ]. Please help me get through this. TIA.

for each_key, (each_file, each_substr) in d.iteritems():  #Giving too many values to unpack error since there are multiple files coming in[no control on how many to expect] 
    for each in each_file:
       print each
       with open(each_file) as f: ## This is giving error as the each is not working as I would expect it to.

Upvotes: 0

Views: 960

Answers (2)

wonder
wonder

Reputation: 3

I figured that out.

for each_key, each_value in d.iteritems():   
each_substring = each_value[1] #Since my substring is appended at the end and am removing it from the each_values list in the below step after saving it here
each_file = each_value[:-1] #Grabbing all files except the last one
for each in each_file:
   print each
   with open(each_file) as f: ## Now this works!!! 

"for each_key, (each_file, each_substr) in d.iteritems():" isn't very efficient if we do not know how many items to expect [that's what it looks like]

Upvotes: 0

tdelaney
tdelaney

Reputation: 77367

You only need 1 loop to extract all of the data. Just use iteritems() and unpack the value tuples to get the strings you want

for each_key, (each_file, each_substr) in d.iteritems():
    print each_key, each_file, each_substr

Upvotes: 1

Related Questions