简体   繁体   中英

Create list item with python dictionary and list elements

Please forgive me for asking, but despite a ton of dictionary.update threads I could not find one that is an example of what I'm want to do.

I have a dictionary:

dictionary = {1:'a', 2:'b', 3:'c', 4:'d'}

and I have a list:

zip_codes = [25840, 26807, 24739, 26501]

I want to add each list item to the dictionary values. The result would look like:

dictionary = {1:('a', 25840), 2:('b', 26807), 3:('c', 24739), 4:('d', 26501)}

The best result I've got is from trying something like this:

for i in zip_codes:
    new_list = [(key,value, i) for key, value in dictionary.items()]

print(new_list)

But this returns the following:

[(1, 'a', 26501), (2, 'b', 26501), (3, 'c', 26501), (4, 'd', 26501)]

Because I am looping through the list items, I get the last list item (26501) as the result. I'm stumped.

I guess, the dictionary key is the order of which you want the zip codes to append?

dictionary = {1:'a', 2:'b', 3:'c', 4:'d'}
zip_codes = [25840, 26807, 24739, 26501]

for i, zip_code in enumerate(zip_codes, 1):
    dictionary[i] = (dictionary[i], zip_code)

print(dictionary)

Which prints

{1: ('a', 25840), 2: ('b', 26807), 3: ('c', 24739), 4: ('d', 26501)}

You might want to have a look at the Python docs about enumerate or this question on StackOverflow about it What does enumerate mean?

With a dict comprehension, you can enumerate through your dictionary and set the new values to the tuple of your existing values and the corresponding zip code:

new_dict = {k:tuple([v,zip_codes[i]]) for i, (k,v) in enumerate(dictionary.items())}
>>> new_dict
{1: ('a', 25840), 2: ('b', 26807), 3: ('c', 24739), 4: ('d', 26501)}

Or very similarly, you can zip the dictionary and the zip codes and iterate through that:

new_dict = {k:tuple([v,z]) for z, (k,v) in zip(zip_codes,dictionary.items())}
>>> new_dict
{1: ('a', 25840), 2: ('b', 26807), 3: ('c', 24739), 4: ('d', 26501)}

You can just use dictionary.update, and, since you are using numbers as dictionary keys, you can use a regular old for loop and don't even have to use enumerate , but you have to remember that list indices start from 0 and your dictionary keys start from 1:

dictionary = {1:'a', 2:'b', 3:'c', 4:'d'}
zip_codes = [25840, 26807, 24739, 26501]

for i in range(1, len(zip_codes)+1):
    d1 = {i:[dictionary[i], zip_codes[i-1]]}
    dictionary.update(d1)

print(dictionary)
>>>{1: ['a', 25840], 2: ['b', 26807], 3: ['c', 24739], 4: ['d', 26501]}

Change new_list to

   new_list = {key: (value, i) for key, value in dictionary.items()}

such that you're making the key be... the key and the overall structure be a dictionary

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