Python Forum
dictionary, list and iteration
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dictionary, list and iteration
#1
a = {7: 0.1, 8: 0.2, 11: 0.1, 12:0.2, 13:0.1, 14: 0.2}
b = [   100,              200,             300         ]
c = {}
expected result 
c = {7: 100,         11:200,          13:300}

I want to replace the   values of a with odd number keys   with a new list b consecutively, 
and output c with the new value having odd number keys in a, is there any short way to do it ?
Reply
#2
a = {7: 0.1, 8: 0.2, 11: 0.1, 12:0.2, 13:0.1, 14:0.2}
b = [100, 200, 300]
c = {key:b[i] for i, key in enumerate(sorted([k for k in a.keys() if k%2]))}
print c
for sake of readability you may prefer
a = {7: 0.1, 8: 0.2, 11: 0.1, 12:0.2, 13:0.1, 14:0.2}
b = [100, 200, 300]
c={}
sorted_odd_keys = sorted([k for k in a.keys() if k%2])
for i, key in enumerate(sorted_odd_keys):
    c[key] = b[i]
print c
or my favorite:

a = {7: 0.1, 8: 0.2, 11: 0.1, 12:0.2, 13:0.1, 14:0.2}
b = [100, 200, 300]
sorted_odd_keys = sorted([k for k in a.keys() if k%2])
c = dict(zip(sorted_odd_keys, b))
print c
Reply
#3
Thanks a lot !
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionary in a list bashage 2 495 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 597 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Sort a list of dictionaries by the only dictionary key Calab 1 452 Oct-27-2023, 03:03 PM
Last Post: buran
  How to add list to dictionary? Kull_Khan 3 951 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  check if element is in a list in a dictionary value ambrozote 4 1,879 May-11-2022, 06:05 PM
Last Post: deanhystad
  Dictionary from a list failed, help needed leoahum 7 1,900 Apr-28-2022, 06:59 AM
Last Post: buran
  how to assign items from a list to a dictionary CompleteNewb 3 1,535 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  List Iteration Help javeeva 2 1,146 Feb-07-2022, 11:23 PM
Last Post: snippsat
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 2,524 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,883 Oct-03-2021, 05:16 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

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