简体   繁体   中英

How to add keys and values to dictionary from lists

I need to create a dictionary with these keys 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 and these values 1, 123, 8765, 0987, 182735, 3459, 9, 0, 2 ,835, 874

I already put these values and keys into lists, a list for each.

year = [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
value = [1, 123, 8765, 0987, 182735, 3459, 9, 0, 2 ,835, 874]

I want a diccionary that has key 2007 value 1 , 2008 123 and so.

I've tried dic[key]=value but it didn't work, i've tried function fromkeys but it didn't work either. please help!!!!

>>> dict(zip(year, value))
{2007: 1, 2008: 123, 2009: 8765, 2010: 987, 2011: 182735, 2012: 3459, 2013: 9, 2014: 0, 2015: 2, 2016: 835, 2017: 874}
year = [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
value = [1, 123, 8765, 987, 182735, 3459, 9, 0, 2 ,835, 874]

s = dict(zip(year, value))
print(s)  

dic[key] = value must work provided the key and value are placed in a loop. A simple way to combine keys and values from two lists is using the zip built-in :

dct = dict(zip(year, value))

You can also use a dict comprehension :

dct = {y: v for y, v in zip(year, value)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM