4

I have created a dictionary which has data like this:

0 = {'Input_file': 'Sample_ Data.xlsx', 'Column_Name': 'Status', 'Column_Filter': 'Active'}

1 = {'Input_file': 'Sample_ Data.xlsx', 'Column_Name': 'Status', 'Column_Filter': 'Inactive'}

how can I iterate through only the values in the same order as 0 and 1 without the keys getting printed. I want to read :- Sample_Data.xlsx , Status, Active in the first iteration and Sample_Data.xlsx , Status, Inactive in the second.

Below is the code I am using to print.

my_dict = reference.to_dict('index')
for column,values in my_dict.items():
    print("{} = {}".format(column, values))
4
  • 2
    my_dict.keys() and my_dict.values() do pretty much what you would think they do ... Commented Jun 6, 2018 at 14:57
  • 1
    That looks like you actually have a nested dictionary where the outer dictionary has only one key and the value is another dictionary (which you then get when calling values on the outer dictionary). Commented Jun 6, 2018 at 15:05
  • Well if you are concerned with the order then my_dict.values() is not for you. You need to get the keys and iterate the dictionaries using keys. Commented Jun 6, 2018 at 15:05
  • 3
    Also, the order of dict.keys() and dict.values() is the same if you don't modify the dictionary between the calls: stackoverflow.com/a/835430/4042267 Commented Jun 6, 2018 at 15:06

2 Answers 2

4

You can use list(dict.keys()) to get the keys as a list. As N_tro_P pointed out, you can use sorted(dict.keys()) to get keys in sorted order and iterate with that.

Sign up to request clarification or add additional context in comments.

Comments

0

There is no guaranteed "order" for dictionary. However, since both dictionaries have the same keys you could cycle through one and use the key against both (or other dictionaries as well). When you "iterate" a dictionary in Python you get the key. Use the key to access the values of the "other" dictionaries.

for keys in my_dict
   print(my_dict[key])
   print(my_other_dict[key])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.