Method digit - Python [duplicate] - python

This question already has answers here:
Create a dictionary with comprehension
(17 answers)
Closed last month.
Is it possible to create a dictionary comprehension in Python (for the keys)?
Without list comprehensions, you can use something like this:
l = []
for n in range(1, 11):
l.append(n)
We can shorten this to a list comprehension: l = [n for n in range(1, 11)].
However, say I want to set a dictionary's keys to the same value.
I can do:
d = {}
for n in range(1, 11):
d[n] = True # same value for each
I've tried this:
d = {}
d[i for i in range(1, 11)] = True
However, I get a SyntaxError on the for.
In addition (I don't need this part, but just wondering), can you set a dictionary's keys to a bunch of different values, like this:
d = {}
for n in range(1, 11):
d[n] = n
Is this possible with a dictionary comprehension?
d = {}
d[i for i in range(1, 11)] = [x for x in range(1, 11)]
This also raises a SyntaxError on the for.

There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.
>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
If you want to set them all to True:
>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}
What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict.

You can use the dict.fromkeys class method ...
>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}
This is the fastest way to create a dictionary where all the keys map to the same value.
But do not use this with mutable objects:
d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!
If you don't actually need to initialize all the keys, a defaultdict might be useful as well:
from collections import defaultdict
d = defaultdict(True)
To answer the second part, a dict-comprehension is just what you need:
{k: k for k in range(10)}
You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__:
>>> class KeyDict(dict):
... def __missing__(self, key):
... #self[key] = key # Maybe add this also?
... return key
...
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}

>>> {i:i for i in range(1, 11)}
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}

I really like the #mgilson comment, since if you have a two iterables, one that corresponds to the keys and the other the values, you can also do the following.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
giving
d = {'a': 1, 'b': 2, 'c': 3}

Consider this example of counting the occurrence of words in a list using dictionary comprehension
my_list = ['hello', 'hi', 'hello', 'today', 'morning', 'again', 'hello']
my_dict = {k:my_list.count(k) for k in my_list}
print(my_dict)
And the result is
{'again': 1, 'hi': 1, 'hello': 3, 'today': 1, 'morning': 1}

Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length
i_s = range(1, 11)
x_s = range(1, 11)
# x_s = range(11, 1, -1) # Also works
d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))])

The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.
Instead of writing
l = []
for n in range(1, 11):
l.append(n)
or
l = [n for n in range(1, 11)]
you should write only
l = range(1, 11)
In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.
To get a new dictionary with all keys set to the same value based on another dict, do this:
old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}
You're receiving a SyntaxError because when you write
d = {}
d[i for i in range(1, 11)] = True
you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like
d[[i for i in range(1, 11)]] = True
and not
d[i for i in range(1, 11)] = True
but lists are not hashable, so you can't use them as dict keys.

A dictionary comprehension is very much like a list comprehension, but we get a dictionary at the end of it, so we need to be assigning key value pairs instead of only values.
Let's say we've got a list of users, where each user information is stored in a tuple. So we have a list with four user tuples. Inside it, they have an ID, a unique identifying number for each user, a username, and a password.
So, we want to create a mapping of usernames to user information.
This is something that you'll be doing very often, especially if you're doing something like web applications and things like that.
users = [
(0, "Bob", "password"),
(1, "code", "python"),
(2, "Stack", "overflow"),
(3, "username", "1234"),
]
username_mapping = {user[1]: user for user in users}
userid_mapping = {user[0]: user for user in users}
print(username_mapping)
"""
Why can this be helpful?
Well, imagine you know a user's username,and you want to get their information out.
You just access, let's say, "Bob," in your username_mapping, and you've got the information out.
"""
print(username_mapping["Bob"]) # (0, "Bob", "password")
# -- Can be useful to log in for example --
username_input = input("Enter your username: ")
password_input = input("Enter your password: ")
_, username, password = username_mapping[username_input]
if password_input == password:
print("Your details are correct!")
else:
print("Your details are incorrect.")
So this is an example of performing some sort of log-in using this structure here, this dictionary comprehension.
This is really helpful because it saves you from having to do another for loop here, to make sure that you are using the right username for their input.

you can't hash a list like that.
try this instead, it uses tuples
d[tuple([i for i in range(1,11)])] = True

Related

How to append a dictionary to key in another dictionary?

So I want my end output to look like this:
answer = {'A':{1,2,3,4},'B':{1,2,3,4}}
How can I do this? I have a few questions though.
How do I make a dictionary without a key pair value. Like {1,2,3,4}
How do I append the {1,2,3,4} to a key ('A').
How do I append the A into the main dictionary(answer)
Essentially I am trying to make this bit in a loop 'A':{1,2,3,4}. Then outside the loop append it to answer.
{1,2,3,4} is a set, not a dict.
You can add the A key and its value (the set) like so:
answer = {}
answer["A"] = {1,2,3,4}
If you have a set, you can add:
>>> s = {1,2}
>>> s
{1, 2}
>>> s.add(3)
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
To iterate:
>>> for item in answer['A']:
... print(item)
...
1
2
3
4
If you want to build a dictionary like that given a list of keys and a set you can do:
list_of_keys = ["A", "B", "C"]
some_set = {1,2,3,4}
my_dict = {key: some_set for key in list_of_keys}
Is there a specific reason why you want to use dictionary and append values into it?
You can use a dictionaries of list:
# Outer Loop
try: answer[i] # i = 'A', 'B'
except KeyError: answer[i] = []
# Inner Loop
answer[i].append(j) # j = 1, 2, 3, 4
print(answer) # {'A':[1,2,2,3,4],'B':[1,1,2,3,4]}
If you do not want duplicates then you can use a set instead of a list.
# Outer Loop
try: answer[i] # i = 'A', 'B'
except KeyError: answer[i] = set()
# Inner Loop
answer[i].add(j) # j = 1, 2, 3, 4
print(answer) # {'A':(1,2,3,4),'B':(1,2,3,4)}
Hope this helps, Cheers!

how to find a match in a dictionary

I have two dictionaries, RFQDict and AwardsDict. I want to take the keys of RFQdict and search through AwardsDict values for matches.
So I tried this
RFQDict = {}
AwardsDict = {}
# Fetch RFQ
RFQref = db.reference('TestRFQ')
snapshot = RFQref.get()
for key, val in snapshot.items():
RFQDict[key] = val
print('{0} => {1}'.format(key, val))
Awardsref = db.reference('DibbsAwards')
dsnapshot = Awardsref.get()
for key, val in dsnapshot.items():
AwardsDict[key] = val
print('{0} => {1}'.format(key, val))
for key in RFQDict:
if key in AwardsDict.values():
print(key+ " Match found")
is this the way to do it or there is a better way and how could return the key and values where the match was found?
In python3 you can do AwardsDict.values() & RFQDict.keys() and you will get a set with the common key/values.
The '&' operator is used for set intersection and works with the dictionary views returned by values() and keys(). More information of the view returned by those methods: https://docs.python.org/3/library/stdtypes.html?highlight=dictview#dictionary-view-objects
If you want to store the keys and values that match, it would probably be best to store the key and value from the second dictionary since if you just store the matching key and value you will have elements like (a, a) which won't really tell you much about where they matched in the second dictionary. Maybe something like this
d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'x': 'a', 'y': 1, 'z': 'c'}
res = [(i, {j: d2[j]}) for i in d1 for j in d2 if i == d2[j]]
print(res)
# [('a': {'x': 'a'}), ('c': {'z': 'c'})]
I would do a list comprehension:
result=[x for x in AwardsDict.values() if x in RFQDict.keys() ]
This way you get a list keeping the duplicates. That is, if a RFQ key is presented in more than one value in AwardsDict. With the & operator you loss that information (as sets only have unique elements).
For example:
RFQDict = {}
AwardsDict = {}
for i in range(5):
RFQDict[i]=0
for i in range(5):
AwardsDict[i]=i
for i in range(5,11):
AwardsDict[i]=i//2 #integer division, i=8 and i=9 get a value of 4
result=[x for x in AwardsDict.values() if x in RFQDict.keys() ]
print('{}'.format(result))
#output [0, 1, 2, 3, 4, 2, 3, 3, 4, 4]

Mapping list elements into their positions (Python)

I have a list of URLs. (We can assume that a given URL is met in the list no more than once.)
I need a fast way to determine which of two URLs is before in the list.
I think, I should create the dict from URL to its position in the list.
What is the easy way (without writing a for loop with manual increasing of the counter) to map elements of a list into their positions in the list?
The best thing I conceived is:
order = {}
i = 0
for item in list:
order[item] = i
i += 1
Now to check if url1 is before url2, I check order[url1] < order[url2].
Can this code be shortened?
This creates your order
order = {k: v for v, k in enumerate(list)}
Example:
L = list('abc')
Your version:
order1 = {}
i = 0
for item in L:
order1[item] = i
i += 1
print(order1)
My version:
order2 = {k: v for v, k in enumerate(L)}
print(order2)
Output:
{'a': 0, 'b': 1, 'c': 2}
{'a': 0, 'b': 1, 'c': 2}
Better don't use listfor your variable name because it is a built-in.
enumerate provides an iterate that gives you the index and the value for each iteration through your list.
If you want to know which comes first for a specific pair of items, you can use the index method on the list:
a = ['cat', 'dog', 'fish']
a.index('cat') < a.index('dog') # True
a.index('fish') < a.index('dog') # False
List of URLs:
urls = ['A', 'B', 'C', 'D']
List of indices:
index = range(len(urls))
Create the dict:
order = dict(zip(urls, index))
Test:
print(order['A'] < order['B']) # True
Demo

How to add dictionary keys with defined values to a list

I'm trying to only add keys with a value >= n to my list, however I can't give the key an argument.
n = 2
dict = {'a': 1, 'b': 2, 'c': 3}
for i in dict:
if dict[i] >= n:
list(dict.keys([i])
When I try this, it tells me I can't give .keys() an argument. But if I remove the argument, all keys are added, regardless of value
Any help?
You don't need to call .keys() method of dict as you are already iterating data_dict's keys using for loop.
n = 2
data_dict = {'a': 1, 'b': 2, 'c': 3}
lst = []
for i in data_dict:
if data_dict[i] >= n:
lst.append(i)
print lst
Results:
['c', 'b']
You can also achieve this using list comprehension
result = [k for k, v in data_dict.iteritems() if v >= 2]
print result
You should read this: Iterating over Dictionaries.
Try using filter:
filtered_keys = filter(lambda x: d[x] >= n, d.keys())
Or using list comprehension:
filtered_keys = [x for x in d.keys() if d[x] >= n]
The error in your code is that dict.keys returns all keys, as the docs mention:
Return a copy of the dictionary’s list of keys.
What you want is one key at a time, which list comprehension gives you. Also, when filtering, which is basically what you do, consider using the appropriate method (filter).

Appending values to dictionary in Python

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)

Categories

Resources