Python Forum
dict printing last key,value out of loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dict printing last key,value out of loop
#6
(Feb-22-2019, 12:51 PM)anna Wrote: I am able to find all key and values in loop, but its printing only last key value out of loop
Yes, because you overwrite the previous value. What you print proves exactly that!!!!
#list for BGP prefixes dicts
bgp_prefix_list = []
for line in ip_prefix:
    if 'ip ip-prefix' in line:
        #dict for BGP prefixes
        bgp_prefix_dict = {}
        prefix_name = line.strip().split(' ')[2]
        subnet = line.strip().split(' ')[6]+"/"+line.strip().split(' ')[7]
        bgp_subnet = str(IPNetwork(subnet))
        bgp_prefix_dict['prefix_name'] = prefix_name
        bgp_prefix_dict['bgp_subnet'] = bgp_subnet
        print(bgp_prefix_dict) #### Able to print current dict
        bgp_prefix_list.append(bgp_prefix_dict)
print(bgp_prefix_list)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
dict printing last key,value out of loop - by anna - Feb-22-2019, 10:26 AM
RE: dict printing last key,value out of loop - by buran - Feb-22-2019, 01:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python3 for loop over a dict ogautier 3 1,448 Feb-25-2022, 10:17 AM
Last Post: Larz60+
  Loop Dict with inconsistent Keys Personne 1 1,642 Feb-05-2022, 03:19 AM
Last Post: Larz60+
  loop printing twice anna 1 2,568 Sep-04-2019, 09:13 AM
Last Post: anna

Forum Jump:

User Panel Messages

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