I am trying to create a dictionary using two lists without the use of zip. can someone help me to finish the code. The function should return an empty dictionary if the lists were empty.
key_list=[1,2,3,4]
value_list=['a','b','c','d']
def list_to_dict(key_list,value_list):
new_dict={}
if len(key_list)!=0 and len(value_list)!=0:
for i in range(len(key_list)):
dict[key_list[i]]=value_list[i]
return new_dict
the output I want is
new_dict={1:'a', 2:'b', 3:'c', 4:'d'}
Your return should go outside the for loop scope, also check for the min lenght of both lists:
def list_to_dict(key_list,value_list):
new_dict = {}
if len(key_list) != 0 and len(value_list) != 0:
for i in range(min(len(key_list), len(value_list))):
new_dict[key_list[i]] = value_list[i]
return new_dict
key_list=[1,2,3,4]
value_list=['a','b','c','d']
def list_to_dict(key_list,value_list):
new_dict={}
if len(key_list)!=0 and len(value_list)!=0 and len(key_list) == len(value_list):
for key, index in enumerate(key_list):
dict[key]=value_list[index]
return new_dict
You had an error in your indentation. Also, both lists need to be the same length to avoid an error, so I added that check. For extra learning, look up enumerate. GL on the rest of your homework :)
Try this.
key_list=[1,2,3,4]
value_list=['a','b','c','d']
def list_to_dict(key_list,value_list):
new_dict={}
if len(key_list)!=0 and len(value_list)!=0:
for i in range(len(key_list)):
new_dict[key_list[i]]=value_list[i]
return new_dict
key_list=[1,2,3,4]
value_list=['a','b','c','d']
def list_to_dict(key_list,value_list):
"""using dict comprehension, creating new key-value pair
for each key present in key list againt the value present in the value list."""
new_dict={key_list[i]:value_list[i] for i in range(len(key_list))}
return new_dict
result = list_to_dict(key_list,value_list)
print(result)
output
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
You can use a dict comprehension:
key_list = [1, 2, 3, 4]
value_list=['a', 'b', 'c', 'd']
def list_to_dict(key_list, value_list):
assert len(key_list) == len(value_list), "Both input lists should have equal length"
return {key_list[i]: value_list[i] for i in range(len(key_list))}
key_list = [1, 2, 3, 4]
value_list=['a', 'b', 'c', 'd']
my_dict={}
def list_dict(key_list,value_list):
for i in range((len(key_list))-1):
my_dict[key_list[i]] = value_list[i] #using loop to add one by one
i=i+1
return my_dict
You can try this for your home work
list_dict(key_list,value_list)
Related
i have this function:
def add_transaction(list_of_items):
for item in list_of_items:
if item not in item_dict.keys():
raise ValueError("You cannot make a transaction containing items that are not present in the items dictionary because it means that the Store does not has those items available, please add the items to the items dictionary first")
transaction_data.append(list_of_items)
return list_of_items
Do you know how it is possible to transform that into a lambda function?
Thanks in advance
Tried to create the lambda function for this function but not sure of how to make it work.
You can do this with set.isssubset() and this hack to raise an exception from a lambda. You'll also need to abuse the or operator to both call transaction_data.append(lst) and return the list.
item_dict = {'a': 1, 'b': 2, 'c': 3}
transaction_data = []
fn = lambda lst: (transaction_data.append(lst) or lst) if set(lst).issubset(item_dict.keys()) else exec("raise ValueError('not in store')")
print(fn(['a', 'c'])) # => ['a', 'c']
print(transaction_data) # => ['a', 'c']
I have a list of dictionaries with hundreds of entries like this
lst = [{'A':'0.1'},{'B':'0.1'},{'C':'0.01'},{'D':'0.0001'},{'E':'0.01'}]
I am trying to sort the key:value pairs into separate lists using dictionary comprehension
lst1 = []
lst2 = []
lst3 = []
lst1.append({key:value for (key,value) in lst if value == '0.1'})
lst2.append({key:value for (key,value) in lst if value == '0.01'})
lst3.append({key:value for (key,value) in lst if value == '0.0001'})
I am then using an if statement to check what list a certain key is in.
variable = 'A'
if variable in lst1:
print('A is in lst one')
When i run the code I get ValueError: not enough values to unpack (expected 2, got 1)
First, don't use list as a name. It's the name of a built-in class and you don't want to overwrite it.
What you're trying to do is something like this:
lst = [{'A':'0.1'},{'B':'0.1'},{'C':'0.01'},{'D':'0.0001'},{'E':'0.01'}]
list1 = [dic for dic in lst if list(dic.values())[0]== '0.1']
list2 = [dic for dic in lst if list(dic.values())[0]== '0.01']
list3 = [dic for dic in lst if list(dic.values())[0]== '0.0001']
print(list1)
print(list2)
print(list3)
outputs:
[{'A': '0.1'}, {'B': '0.1'}]
[{'C': '0.01'}, {'E': '0.01'}]
[{'D': '0.0001'}]
Note that list(dic.values()) wouldn't have made any sense (it would produce an error) had I overwritten list.
And later:
variable = 'A'
for item in list1:
if variable in item.keys():
print('A is in list one')
which can be encapsulated in a function:
def find_key(variable):
for item in list1:
if variable in item.keys():
print(f'{variable} is in list one')
find_key('A')
A is in list one
Now, do you really need to use dictionaries with one key, value pair each one? Do you need to store those in a list? I'm not sure what you're trying to do, but seems like a XY problem. Try to think whether there is a simpler, more elegant way of doing it.
The same for the second part: are you going to make a separate function for each list?
This works perfectly!
lst = [{'A':'0.1'},{'B':'0.1'},{'C':'0.01'},{'D':'0.0001'},{'E':'0.01'}]
print(dict([list(d.items())[0] for d in lst if list(d.items())[0][1] == '0.1']))
print(dict([list(d.items())[0] for d in lst if list(d.items())[0][1] == '0.01']))
print(dict([list(d.items())[0] for d in lst if list(d.items())[0][1] == '0.0001']))
output
{'A': '0.1', 'B': '0.1'}
{'C': '0.01', 'E': '0.01'}
{'D': '0.0001'}
thanks to Psidom
I want to separate each (key, value) pair from a dictionary and want to call each value by its key name.
I have two lists,
1. ListA = [1, 2, 3, 4, 5]
2. ListB = ['A', 'B', 'C', 'D', 'E']
Now I have created a dictionary like this,
Dict = {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}
So, now if I want to see value for each key, I have to type:
Dict[key].
Now I expect my result to be like:
If I ask for the value of each key, I have to just type key not Dict[key]
and it should give me the answer.
Typing 1 should give A.
Typing 2 should give B.
You can somehow do like this but you if you can simply access below is not a very good idea honestly. You can set key as attribute of an object.
But it wont work for the dictionary you have my Input Dictionary is {"key1":"Apple"}
class MyDict:
def __init__(self,input_dict):
for key,value in input_dict.items():
setattr(self,key,value) #setting key as attribute
obj = MyDict({"key1":"Apple"}) #new instance
print(obj.key1) # this will print Apple
But still it wont work like obj.1 better not to mess it.
If you want to loop over dictionary values, you can use Dict.values():
for v in Dict.values():
print(v)
# > 'A'
# > 'B'
# ...
Inside a while true loop, keep popping items from your lists until you run into an IndexError like this:
ListA = [1, 2, 3]
ListB = ['A', 'B', 'C']
DictC = {}
while True:
try:
DictC[ListA.pop(0)] = ListB.pop(0)
except IndexError:
break
print(DictC)
I am parsing some XML data from Open Street Map into JSON (later to be uploaded into a database). It is large, so I am using iterparse. I have some tags that look like this
<tag 'k'=stringA:stringB:stringC 'v'=value>
which I want to parse into
{stringA: {stringB: {stringC: value} } }
I have done so with an ugly hardcode. However, I would like to create a function that uses recursion to address the same issue in case the 'k' attribute value contains arbitrarily as many ':'.
I created this
def nestify(l):
"""Takes a list l and returns nested dictionaries where each element from
the list is both a key to the inner dictionary and a value to the outer,
except for the last element of the list, one which is only a value.
For best understanding, feed w = [ 'a', 'b', 'c', 'd', 'e', 'f', 'v'] to the
function and look at the output."""
n = len(l)
if n==2:
key = l[0]
value = l[1]
else:
key = l[0]
value = nestify(l[1:])
return {key:value}
which works. (You have to make the keys and value into a list first.) Except not really, because it always makes a new dictionary. I need it to respect the previous data and integrate. For example, if my parser encounters
<tag 'k'=a:b:c 'v'=1 />
and then in the same element
<tag 'k'=a:d:e 'v'=2 />
I need it to make
{a: {'b': {'c' : 1}, 'd' : {'e' : 2}}}
and not
{a: {'b' : {'c' : 1}}}
{a: {'d' : {'e' : 2}}}
I have tried this code:
def smart_nestify(l, record):
n = len(l)
if n==2:
key = l[0]
value = l[1]
else:
key = l[0]
value = smart_nestify(l[1:], key)
if key not in record:
return {key:value}
else:
record[key] = value
return record
but it still writes over and returns only the latest record. Why is that? How can I fix this code?
Here is a "smarter" nestify that merges a list l into the dictionary record:
def smarter_nestify(l, record):
if len(l) == 2:
return {l[0]: l[1]}
key = l.pop(0)
record[key] = smarter_nestify(l, record.get(key, {}))
return record
Each time through the recursion, it pops the first element from the list l.pop(0) and merges the value from the next level of the dictionary record.get(key, {}).
You can call it with two lists like this:
l = ['a', 'b', 'c', 1]
record = smarter_nestify(l, {})
l = ['a', 'd', 'e', 2]
record = smarter_nestify(l, record)
print record
Sometimes it is better to just use iteration rather than recursion. Here’s the iterative answer.
g_values = dict()
def make_nested(l):
"""
l is the array like you have for nestify
e.g., ['a', 'b', 'c', 1 ] or ['a', 'd', 'e', 2]
"""
global g_values
value = l[-1] ; l = l[:-1]
last_dict = None
for x in l[:-1]:
mp_temp = last_dict if last_dict is not None or g_values
last_dict = mp_temp.get(x)
if last_dict is None:
mp_temp[x] = dict()
last_dict = mp_temp[x]
last_dict[l[-1]] = value
While I didn’t test it, you could also try something like this recursively:
def make_nested(values, l):
if len(l == 2):
values[l[0]] = l[1]
return
mp = values.get(l[0])
if mp is None:
values[l[0]] = dict()
make_nested(values[l[0]], l[1:])
else:
make_nested(mp, l[1:])
I have a dictionary to which I want to append to each drug, a list of numbers. Like this:
append(0), append(1234), append(123), etc.
def make_drug_dictionary(data):
drug_dictionary={'MORPHINE':[],
'OXYCODONE':[],
'OXYMORPHONE':[],
'METHADONE':[],
'BUPRENORPHINE':[],
'HYDROMORPHONE':[],
'CODEINE':[],
'HYDROCODONE':[]}
prev = None
for row in data:
if prev is None or prev==row[11]:
drug_dictionary.append[row[11][]
return drug_dictionary
I later want to be able to access the entirr set of entries in, for example, 'MORPHINE'.
How do I append a number into the drug_dictionary?
How do I later traverse through each entry?
Just use append:
list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']
You should use append to add to the list. But also here are few code tips:
I would use dict.setdefault or defaultdict to avoid having to specify the empty list in the dictionary definition.
If you use prev to to filter out duplicated values you can simplfy the code using groupby from itertools
Your code with the amendments looks as follows:
import itertools
def make_drug_dictionary(data):
drug_dictionary = {}
for key, row in itertools.groupby(data, lambda x: x[11]):
drug_dictionary.setdefault(key,[]).append(row[?])
return drug_dictionary
If you don't know how groupby works just check this example:
>>> list(key for key, val in itertools.groupby('aaabbccddeefaa'))
['a', 'b', 'c', 'd', 'e', 'f', 'a']
It sounds as if you are trying to setup a list of lists as each value in the dictionary. Your initial value for each drug in the dict is []. So assuming that you have list1 that you want to append to the list for 'MORPHINE' you should do:
drug_dictionary['MORPHINE'].append(list1)
You can then access the various lists in the way that you want as drug_dictionary['MORPHINE'][0] etc.
To traverse the lists stored against key you would do:
for listx in drug_dictionary['MORPHINE'] :
do stuff on listx
To append entries to the table:
for row in data:
name = ??? # figure out the name of the drug
number = ??? # figure out the number you want to append
drug_dictionary[name].append(number)
To loop through the data:
for name, numbers in drug_dictionary.items():
print name, numbers
If you want to append to the lists of each key inside a dictionary, you can append new values to them using + operator (tested in Python 3.7):
mydict = {'a':[], 'b':[]}
print(mydict)
mydict['a'] += [1,3]
mydict['b'] += [4,6]
print(mydict)
mydict['a'] += [2,8]
print(mydict)
and the output:
{'a': [], 'b': []}
{'a': [1, 3], 'b': [4, 6]}
{'a': [1, 3, 2, 8], 'b': [4, 6]}
mydict['a'].extend([1,3]) will do the job same as + without creating a new list (efficient way).
You can use the update() method as well
d = {"a": 2}
d.update{"b": 4}
print(d) # {"a": 2, "b": 4}
how do i append a number into the drug_dictionary?
Do you wish to add "a number" or a set of values?
I use dictionaries to build associative arrays and lookup tables quite a bit.
Since python is so good at handling strings,
I often use a string and add the values into a dict as a comma separated string
drug_dictionary = {}
drug_dictionary={'MORPHINE':'',
'OXYCODONE':'',
'OXYMORPHONE':'',
'METHADONE':'',
'BUPRENORPHINE':'',
'HYDROMORPHONE':'',
'CODEINE':'',
'HYDROCODONE':''}
drug_to_update = 'MORPHINE'
try:
oldvalue = drug_dictionary[drug_to_update]
except:
oldvalue = ''
# to increment a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s" % newval
# to append a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s,%s" % (oldval,newval)
The Append method allows for storing a list of values but leaves you will a trailing comma
which you can remove with
drug_dictionary[drug_to_update][:-1]
the result of the appending the values as a string means that you can append lists of values as you need too and
print "'%s':'%s'" % ( drug_to_update, drug_dictionary[drug_to_update])
can return
'MORPHINE':'10,5,7,42,12,'
vowels = ("a","e","i","o","u") #create a list of vowels
my_str = ("this is my dog and a cat") # sample string to get the vowel count
count = {}.fromkeys(vowels,0) #create dict initializing the count to each vowel to 0
for char in my_str :
if char in count:
count[char] += 1
print(count)