简体   繁体   中英

How to create a dictionary using python list comprehension from 2 list

This is my code:

a=[1,2,3,4,5,6,7]
b=[8,9,10,11,12,13,14]
c=[{i:j} for i in a for j in b]
print(c)

Output is

[{1: 8}, {1: 9}, {1: 10}, {1: 11}, {1: 12}, {1: 13}, {1: 14}, {2: 8}, {2: 9}, {2: 10}, {2: 11}, {2: 12}, {2: 13}, {2: 14}, {3: 8}, {3: 9}, {3: 10}, {3: 11}, {3: 12}, {3: 13}, {3: 14}, {4: 8}, {4: 9}, {4: 10}, {4: 11}, {4: 12}, {4: 13}, {4: 14}, {5: 8}, {5: 9}, {5: 10}, {5: 11}, {5: 12}, {5: 13}, {5: 14}, {6: 8}, {6: 9}, {6: 10}, {6: 11}, {6: 12}, {6: 13}, {6: 14}, {7: 8}, {7: 9}, {7: 10}, {7: 11}, {7: 12}, {7: 13}, {7: 14}]

But I want like:

[{1: 8, 2: 9, 3: 10, 4: 11, 5: 12, 6: 13, 7: 14}]

How to achieve this?

  • To pair several list together you need to use zip operation zip(a, b) ,
  • You may use dict comprehension notation or dict constructor
  • Wrap in an array if needed
c = dict(zip(a, b))   # {1: 8, 2: 9, 3: 10, 4: 11, 5: 12, 6: 13, 7: 14}
c = [dict(zip(a, b))] # [{1: 8, 2: 9, 3: 10, 4: 11, 5: 12, 6: 13, 7: 14}]

c = {i: j for i, j in zip(a, b)}   # {1: 8, 2: 9, 3: 10, 4: 11, 5: 12, 6: 13, 7: 14}
c = [{i: j for i, j in zip(a, b)}] # [{1: 8, 2: 9, 3: 10, 4: 11, 5: 12, 6: 13, 7: 14}]

Your notation [{:} for _ in _] was creating a dict for each iteration, resulting in mulitple dicts in a list [{}, {}, {}]

Use dict with zip

Ex:

a=[1,2,3,4,5,6,7]
b=[8,9,10,11,12,13,14]

print(dict(zip(a, b)))
# --> {1: 8, 2: 9, 3: 10, 4: 11, 5: 12, 6: 13, 7: 14}

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