Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

convert 2 lists to a dictionary in python

""" How to convert 2 lists into a dictionary in python """
# list used for keys in dictionary
students = ["Angela", "James", "Lily"]

# list of values
scores = [56, 76, 98]

# convert lists to dictionary
student_scores = dict(zip(students, scores))

# print the dictionary
print(student_scores)

""" result should be
student_scores: -{
        Angela: 56,
        James: 76,
        Lily: 98
    },
"""
Comment

python join two lists as dictionary

# using zip()
# to convert lists to dictionary

# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
  
res = dict(zip(test_keys, test_values))
Comment

Convert two lists into a dictionary in Python

>>> students = ["Cody", "Ashley", "Kerry"]
>>> grades = [93.5, 95.4, 82.8]
>>> {s: g for s, g in zip(students, grades)}
{'Cody': 93.5, 'Ashley': 95.4, 'Kerry': 82.8}
Comment

merge a list of dictionaries python

>>> from collections import ChainMap
>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
>>> dict(ChainMap(*a))
{'b': 2, 'c': 1, 'a': 1, 'd': 2}
Comment

python merge list of dict into single dict

l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}]
d = {k: v for x in l for k, v in x.items()}
print(d)
# {'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
Comment

Converting Two Lists Into a Dictionary

column_names = ['id', 'color', 'style']
column_values = [1, 'red', 'bold']

# Convert two lists into a dictionary with zip and the dict constructor
name_to_value_dict = dict(zip(column_names, column_values))

# Convert two lists into a dictionary with a dictionary comprehension
name_to_value_dict = {key:value for key, value in zip(column_names, column_values)}

# Convert two lists into a dictionary with a loop
name_value_tuples = zip(column_names, column_values) 
name_to_value_dict = {} 
for key, value in name_value_tuples: 
  if key in name_to_value_dict: 
    pass # Insert logic for handling duplicate keys 
  else: 
    name_to_value_dict[key] = value
Comment

merge two list of dictionaries python with string

import pandas as pd

l1 = [{'id': 9, 'av': 4}, {'id': 10, 'av': 0}, {'id': 8, 'av': 0}]
l2 = [{'id': 9, 'nv': 45}, {'id': 10, 'nv': 0}, {'id': 8, 'nv': 30}]

df1 = pd.DataFrame(l1).set_index('id')
df2 = pd.DataFrame(l2).set_index('id')
df = df1.merge(df2, left_index=True, right_index=True)
df.T.to_dict()
# {9: {'av': 4, 'nv': 45}, 10: {'av': 0, 'nv': 0}, 8: {'av': 0, 'nv': 30}}
Comment

convert 2 lists into dictionary

# convert 2 list into dictionary
a = ['gsw','lakers','clippers']
b = [1,2,3]
my_dict = dict(zip(a,b))
print(my_dict)					# {'gsw': 1, 'lakers': 2, 'clippers': 3}
Comment

python two list into dictinaray

index = [1, 2, 3]
languages = ['python', 'c', 'c++']

dictionary = dict(zip(index, languages))
print(dictionary)
Comment

merge lists dictionary

# (*) unpacking operator
    # for positional vs keyword argument, see "03 functions"
    # for packing, see "03 functions"       
# * can unpack iterables eg tuple, list, strings etc to its elements. 
# ** can only unpack dictionary

# convert range til list
l1 = [range(5)]     
print(l1)
#[range(0, 5)]

l = [*range(5)]     # * unpacking operator
print(l)
#[0, 1, 2, 3, 4]


# unpacking a collection
my_tuple = (1, 2, 3, 4, 5, 6, 7)
i1, *i2, i3, i4 = my_tuple      # the middle part of the tuple gets unpacked into a list in i2
print(i1)
print(i2)
print(i3)
print(i4)
# 1
# [2, 3, 4, 5]
# 6
# 7


# merge containers
my_tuple = (1, 2, 3)
my_list = [4, 5, 6]
merged_list = [*my_tuple, *my_list]
print(merged_list)
# [1, 2, 3, 4, 5, 6]

dict_a = {'a':1, 'b':2}
dict_b = {'c':3, 'd':4}
merged_dict = {**dict_a, **dict_b}
print(merged_dict)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}


# unpacking arguments passed to function calls
# Ex 1: unpack collections into func arguments
def foo(a, b, *args, **kwargs):
    print(a, end = ' ')
    for arg in args:    #args is unpacked into an iterable object
        print(arg, end = ' ')
    for key in kwargs:
        print(key, kwargs[key], end = ' ')

foo(1, 2, 3, 4, 5, six=6, seven=7)
# 1 3 4 5 six 6 seven 7 
values = (1, 2, 3, 4, 5)
mydict = {'eight': 8, 'nine': 9}
foo(*values, **mydict)    #NB! * unpacking operator, otherwise passing a tuple + dict
#1 3 4 5 eight 8 nine 9   #NB! ** for dict, otherwise only get keys


# Ex 2: matching parameters with unpacked arguments
def myFun(a, b, c):
    print("a:", a)
    print("b:", b)
    print("c:", c)
     
# keys in dictionary must be the same as names of parameters
kwargs = {"a" : "One", "b" : "Two", "c" : "Three"}  #dictionary
myFun(**kwargs)     # passing a dictionary into myFun() by unpacking it and pass individual key:value pair
# a: One
# b: Two
# c: Three
Comment

PREVIOUS NEXT
Code Example
Python :: sorted set in python 
Python :: how to get the memory location of a varible in python 
Python :: run a shell script from python 
Python :: how to get index in python 
Python :: stackoverflow: install old version of networkx 
Python :: discord chatterbot python 
Python :: python enable pyqt errors 
Python :: python display text in label on new line 
Python :: PySimpleGUI multifiles select 
Python :: how to save string json to json object python 
Python :: ord() python 
Python :: menor valor lista python 
Python :: create django model field based on another field 
Python :: extra import on django 
Python :: numpy sort multidimensional array 
Python :: calculate the surface area of a cylinder python 
Python :: plt grid linestyles options 
Python :: what is an object in python 
Python :: rotate existing labels python 
Python :: django admin text box 
Python :: turtle screen 
Python :: Python use number twice without variable 
Python :: ski learn decision tree 
Python :: df max count syntax 
Python :: mid point circle drawing 
Python :: python get dir from path 
Python :: numpy if zero is present 
Python :: search mean in python using pandas 
Python :: accumulator programming python 
Python :: convert int to ascii python 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =