Add list data to a dictionary - python

So I have a dictionary
dict={'Andrew':5, 'Brian':3, 'Clive':2, 'David':4}
it contains the names of volunteers and the number of times that they have volunteered for a particular duty. The dictionary is regularly updated by providing both the dictionary and a list to a function upd.
For the current update the following list has been declared - each name represents a new volunteer session:
ulist = ['Brian', 'David', 'Peter']
Write and demonstrate the function upd. Any ideas where to start
I have
def upd(lst):
I know its not much, but I am just learning about lists and dictionaries.
TIA
David.
EDIT:
My apologies, I should have been more specific
the upd function should create the dictionary and append/increment when a user is found, if not, it should create new user

Here is what I imagine your requirements are:
If a name in ulist is already in the dictionary, increment the value associated with it, otherwise create an entry for the name and initialize the value to 1.
This code is quite simple really. Just iterate through each name in ulist and check to see if it is in my_dictionary, if not then add it, if so then increment it.
my_dictionary = {'Andrew':5, 'Brian':3, 'Clive':2, 'David':4}
ulist = ['Brian', 'David', 'Peter']
def udp(lst):
for name in lst:
if name in my_dictionary:
my_dictionary[name] += 1
else:
my_dictionary[name] = 1
udp(ulist)
print(my_dictionary)
Results:
{'Andrew': 5, 'Brian': 4, 'Clive': 2, 'David': 5, 'Peter': 1}
Note: You named your dictionary dict which is technically a keyword in Python so I recommend changing it to something like my_dictionary as shown in my example.

Related

How to have key,key value pair and only keys in python dictionary?

I have a python dictionary,
P_dic = {'ID': 'STD1'}
and I have output corresponding to this in a list.
Lst = ['Len','Lin','lon']
So basically for an ID, there are three values associated to it.
I want to have something like,
Result = {'ID': 'STD1'}: {'Len','Lin','lon'}}
I am unsure of how to save this inside python dictionary. Please help.
This may help you:
P_dict['lst'] = Lst # from Lst variable
or
P_dict['lst'] = ['Len','Lin','lon'] # direct assignment

search through a nested dictionary and record the steps

say I have a dictionary like this:
profile = {'Person':{'name':['John'], 'Description':['smart']}}
I am looking for a piece of code that searches for 'John', and 'Description', but doesn't know where they are in the nested dictionary. I also want to the code to print something like this:
John is located in the value of profile['Person']
Description is located in the key of profile['Person']
How can I do that? Any help will be appreciated. Thank you
Learn how to iterate through a nested dictionary. In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Indexing [ ] is used to access an element of a nested dictionary
profile = {'Person':{'name':['John'], 'Description':['smart']},'Person1':{'name':['John1'], 'Description':['smart1']}}
for p_id, p_info in profile.items():
for key in p_info:
if p_info[key][0] == "John":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")
if p_info[key][0] == "smart":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")

Creating a dict containing a sub-dict as the new value with the index as the key

I have a dictionary currently setup as
{'name': 'firm', 'name':'firm', etc},
Where keys are analyst names and values are analyst firms.
I am trying to create a new dictionary where the new values are the old k,v pairs and the associated key is simply the index (1, 2, 3, 4, etc).
Current code is below:
num_analysts = len(analysts.keys())
for k,v in analysts.items():
analysts_dict = dict.fromkeys(range(num_analysts), [k,v])
Current result
Each numeric key is getting given the same value (old k,v pair). What is wrong with my expression?
You can enumerate the items and convert them to a dictionary. However, dictionaries, in general, are not ordered. This means that the keys may be assigned essentially randomly.
dict(enumerate(analysts.items(), 1))
#{1: ('name1', 'firm1'), 2: ('name2', 'firm2')}
Enumerate and dictionary comprehension for this
d = {'name1': 'firm1', 'name2': 'firm2'}
d2 = {idx: '{}, {}'.format(item, d[item]) for idx, item in enumerate(d, start = 1)}
{1: 'name1, firm1', 2: 'name2, firm2'}
There are already effective answer posted by others. So I may just put the reason why your own solution does't work properly. It may caused by lazy binding. There are good resource on: http://quickinsights.io/python/python-closures-and-late-binding/
Because late binding will literally pick up the last one in dictionary you created. But this last one is not "virtually last one", it is determined by the OS. (Other people already give some explanation on dict data-structure.)
For each time you run in python command line the result may change. If you put the code in .py file, For each time you run in IDE, the result will be same.(always the last one in dict)
During each iteration, analysts_dict is assigned value based on the result of dict.items().
However, you should use comprehension to generate the final result in one line,
E.g. [{i: e} for i, e in enumerate(analysts.items())]
analysts = {
"a": 13,
"b": 123,
"c": 1234
}
num_analysts = len(analysts.keys())
analysts_dict = [{i: e} for i, e in enumerate(analysts.items())]
print(analysts_dict)
>> [{0: ('a', 13)}, {1: ('b', 123)}, {2: ('c', 1234)}]
This code
for k,v in analysts.items():
analysts_dict = dict.fromkeys(range(num_analysts), [k,v])
loops over the original dict and on each loop iteration it creates a new dict using the range numbers as the keys. By the way, every item in that dict shares a reference to a single [k, v] list object. That's generally a bad idea. You should only use an immutable object (eg None, a number, or a string) as the value arg to the dict.fromkeys method. The purpose of the method is to allow you to create a dict with a simple default value for the keys you supply, you can't use it to make a dict with lists as the values if you want those lists to be separate lists.
The new dict object is bound to the name analysts_dict. On the next loop iteration, a new dict is created and bound to that name, replacing the one just created on the previous loop, and the replaced dict is destroyed.
So you end up with an analysts_dict containing a bunch of references to the final [k, v] pair read from the original dict.
To get your desired result, you should use DYZ's code, which I won't repeat here. Note that it stores the old name & firm info in tuples, which is better than using lists for this application.

Indexing with string? [Python]

I am learning python this semester and I came across some code I do not understand well.
firstVal = examples[0][firstName]
where examples is list of dictionary
and firstName is a Str
Could someone help explain to me what it is doing?
Thanks!
Alright, so basically what it is doing is it is taking the first dictionary from the list of dictionaries, and accessing the value in the key for firstName.
For ex:
examples is some thing like:
[{'John': 'Doe', 'Jack': 'Peterson', 'Jake': 'Paul'}, {'Martin': 'Richardson', 'Luke': 'Skywalker', 'Logan': 'Paul'}]
Doing examples[0], get's you the first element of that list, which is: {'John': 'Doe', 'Jack': 'Peterson', 'Jake': 'Paul'}
Now, let's say firstName = 'Jack'.
Then, examples[0][firstName] is the same as examples[0]['Jack'] which is 'Peterson' because the value for the key 'Jack' is 'Peterson'
Please tell me if you need me to elaborate more ;)
The examples[0] is getting the first dictionary in the list of dictionaries examples. Then it is accessing the key defined by the string firstName.
For example,
examples = [{'1':2, '3':4}, {'5':6, '7':8}]
firstName = '1'
firstVal = examples[0][firstName] # will output 2
Let's take a look at it closely.
If examples is a list of dictionaries, then examples[0] must be the first dictionary in that list.
Then, we look for the key firstName in that dictionary.
We finally assign this value to firstVal.
So in a sentence, this line takes the first dictionary in the list, finds the value of the key firstName, and assigns it to firstVal.

Create a python dictionary from a list

I'm trying to create a dictionary from a list in python. I'm creating alist from a .txt fril in the same directory as the .py file. But I don't understand how I create a dictionary without manually assigning a key to every value?
l = open ("Luther_King.txt").read()
words = l.split( )
print (words)
The print statement is just to check if it did in fact split the string into a list. Am I going to need to manually assign a key for every word or can I generate one somehow?
Unfortunately you have to have key and value. You can try this, send two list and merge them in a dictionary. You can just send a very basic list in order to have a key like : 1, 2, 3, 4, 5, ...
def get_dic_from_two_lists(keys, values):
return {keys[i]: values[i] for i in range(keys)}
I am going to take a wild guess- and suggest you use range of the size of your list to generate keys.Then zip them together,you'll have your dictionary!!
#Your original list
['Jack', 'Luther', 'Dima', 'Vijay']
#Generate another list,which will be your keys
key_list=range(1,5,1)
newdict = dict(zip(key_list, words))
#This is how new dict would look
{1: 'Jack', 2: 'Luther', 3: 'Dima', 4: 'Vijay'}

Categories