Related
I need to create a program that takes a file containing DNA and converts the open reading frame into protein data. I need to run the function once "ATG" occurs and until the stop codons "TAG" "TAA" or "TGA" occur.
I'm new to programming and this is what I have,
map = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
DNAlist = []
DNAlist1 = []
DNAlist2 = []
protein = []
for i in range(0, len(DNA), 3):
DNAlist.append(DNA[i:i+3])
for i in range(1, len(DNA), 3):
DNAlist1.append(DNA[i:i+3])
for i in range(2, len(DNA), 3):
DNAlist2.append(DNA[i:i+3])
while True:
if elements in DNAlist2 == 'TAG' or 'TAA' or 'TGA':
False
else:
protein = ''.join([map[elements] for elements in DNAlist2])```
A sample output would be
MLLGSFRLIPKETLIQVAGSSPCNLS
M
MGMTPRLGLESLLE
MTPRLGLESLLE
well tried without using Biopython, went only for forward strand (no reverse) and used the translated sequence
found two ways, I am sure these are non-optimal approaches, I am waiting for somebody better here How to find a open reading frame in Python are fastest ways I suppose.
first one gives you ORFs even if there is no stop codon (sequence doesnt terminate so no '_' for stop codon presence :
mappy = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
# for i in mappy:
# print(mappy[i])
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
DNAlist1 = []
DNAlist2 = []
DNAlist3 = []
# protein = []
def revProt(dna_list):
proteinz = []
for elements in dna_list:
if len(elements) == 3:
proteinz.append(mappy[elements])
# proteinz = ''.join(proteinz)
return ''.join([ i for i in reversed(proteinz)])
for i in range(0, len(DNA), 3):
DNAlist1.append(DNA[i:i+3])
for i in range(1, len(DNA), 3):
DNAlist2.append(DNA[i:i+3])
for i in range(2, len(DNA), 3):
DNAlist3.append(DNA[i:i+3])
# for i in [DNAlist1] : #, DNAlist2, DNAlist3]:
for i in [DNAlist1, DNAlist2, DNAlist3]:
protein = revProt(i)
print(''.join(protein), type(''.join(protein)))
seqs = []
j = 0
orf = []
while True:
if j <= len(protein)-1:
if protein[j] == '_' :
if orf[0] == 'M':
orf.append('_')
seqs.append(''.join([i for i in reversed(orf)]))
orf = []
else :
orf = []
orf.append('_')
if protein[j] not in [ '_' , 'M'] :
orf.append(protein[j])
if protein[j] == 'M':
orf.append(protein[j])
seqs.append(''.join([i for i in reversed(orf)]))
else :
break
j += 1
print(seqs, '\n')
output:
QSAVRIM_A_ELLSELGLRPTMGMYGSNAVHS <class 'str'>
['MIRVASQ', 'MTPRLGLESLLE_', 'MGMTPRLGLESLLE_'] -----> here sequences 1st is at the end of DNA so no stop
LH_ES_EPKNWFLS_DLDRP_GWTVQTL_MA <class 'str'>
['M_']
SISSPDNLSIGFSVRIWTAPDDGHLRL_SCP <class 'str'>
[]
second way even more cumbersome :
import itertools
mappy = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
DNAlist1 = []
DNAlist2 = []
DNAlist3 = []
def Prot(dna_list):
proteinz = []
for elements in dna_list:
if len(elements) == 3:
proteinz.append(mappy[elements])
# proteinz = ''.join(proteinz)
return proteinz
def Met(protein):
met = [i for i, x in enumerate(protein) if x == "M"]
return met
def Stop(protein):
stop = [i for i, x in enumerate(protein) if x == "_"]
return stop
for i in range(0, len(DNA), 3):
DNAlist1.append(DNA[i:i+3])
for i in range(1, len(DNA), 3):
DNAlist2.append(DNA[i:i+3])
for i in range(2, len(DNA), 3):
DNAlist3.append(DNA[i:i+3])
for i in [DNAlist1, DNAlist2, DNAlist3]:
protein = Prot(i)
print(''.join(protein), type(''.join(protein)))
met = Met(protein)
# print('met : ', met)
stop = Stop(protein)
# print('stop : ' , stop)
# print('------------------')
orf = [i for i in list(itertools.product(met, stop)) if i[0] < i[1]]
print(orf)
orf_p = [''.join(protein[j[0]:j[1]]) for j in orf]
orf_pp = [i for i in orf_p]
for y in orf_p:
# print(y, type(y))
if '_' in y:
# print('ok')
orf_pp.remove(y)
print('orf_pp : ',orf_pp)
print('______________')
output:
SHVANSGYMGMTPRLGLESLLE_A_MIRVASQ <class 'str'>
[(8, 22), (8, 24), (10, 22), (10, 24)]
orf_pp : ['MGMTPRLGLESLLE', 'MTPRLGLESLLE'] ----->here the sequences
______________
AM_LTQVTWG_PRDLD_SLFWNKPE_SE_HL <class 'str'>
[(1, 2), (1, 10), (1, 16), (1, 25), (1, 28)]
orf_pp : ['M']
______________
PCS_LRLHGDDPATWIRVSFGISLNDPSSIS <class 'str'>
[]
orf_pp : []
______________
shorter (probably faster copied from : How to find a open reading frame in Python
import re
mappy = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',
}
# for i in mappy:
# print(mappy[i])
DNA = 'AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG'
def Prot(dna_list):
proteinz = []
for elements in dna_list:
if len(elements) == 3:
proteinz.append(mappy[elements])
return proteinz
pattern = re.compile(r'(?=(ATG(?:...)*?)(?=TAG|TGA|TAA))')
def revcomp(dna_seq):
return dna_seq[::-1].translate(str.maketrans("ATGC","TACG"))
def orfs(dna):
return set(pattern.findall(dna) + pattern.findall(revcomp(dna)))
for j in orfs(DNA):
# print(j, type(j))
DNAlistz = []
for i in range(0, len(j), 3):
DNAlistz.append(j[i:i+3])
print(''.join(Prot(DNAlistz)))
print('+++++++++++++')
output this time with reverse strand translation too:
MGMTPRLGLESLLE
MTPRLGLESLLE
M
MLLGSFRLIPKETLIQVAGSSPCNLS
+++++++++++++
So i have my hand of cards that i randomly dealt from a deck but i need to remove the duplicate numbers in my hand. I have no idea where to start.
this is an example of what my hand would look like before removing the pairs:
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
and this is what i've tried:
no_pairs=[]
l.sort()
for i in range(len(l)):
for j in (i+1, len(l)):
if i[-2] not in j:
no_pairs.append(i)
when i do this, it keeps saying
TypeError: 'int' object is not subscriptable
Strip the final character when iterating through the list of strings.
If you're just looking for the number, ignoring the suit, then you just need to strip the suit from the number before comparing it to an array of the numbers you've already sorted, and then adding both the stripped value to the array of numbers, and the original value to the final output. This should work:
l.sort()
sorted_num = []
final = []
for i in l:
if i[:-1] not in sorted_num:
sorted_num.append(i[:-1])
final.append(i)
When run, this gives the value of final as:
['10♢', '2♠', '3♢', '4♡', '6♠', '7♠', '8♢', '9♠', 'A♠', 'J♣', 'K♡', 'Q♠']
Check for the occurrence of each element in the list, and append only if occurs once.
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs=[]
for i in set(l):
if l.count(i)==1:
no_pairs.append(i)
Get first character of items with item[0], then check it is a number with num.isdigit() method and add it to no_pairs list.
l=['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢', '2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs = []
for item in l:
num = item[0]
if num.isdigit():
num = int(num)
no_pairs.append(int(num))
print(no_pairs)
#output :
[6, 6, 7, 1, 8, 2, 9, 8, 7, 9, 1, 2, 2, 3, 6, 4, 4]
Your i is an int, you can achieve i[2] (for the error). Then I really don't know where your code was going, so I didn't try to fix I wrote a new one.
I'd suggest you keep track of the numbers you already added, so that you know if you add the card or not
l = ['6♠', '6♣', '7♢', '10♣', '8♣', '2♣', '9♠', '8♢', '7♠', 'K♢', '9♡', 'Q♡', '10♢',
'2♠', 'K♡', '2♢', '3♢', 'Q♢', '6♡', '4♣', 'A♡', '4♡', 'A♠', 'A♣', 'J♣', 'Q♠']
no_pairs = []
nb_cards = set()
for card in l:
nb_card = card[:-1]
if nb_card not in nb_cards:
nb_cards.add(nb_card)
no_pairs.append(card)
print(no_pairs) # ['6♠', '7♢', '10♣', '8♣', '2♣', '9♠', 'K♢', 'Q♡', '3♢', '4♣', 'A♡', 'J♣']
You can replace the set by a list, but that woul dbe just less performant
I have the following list in python.
list = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
how can I remove pairs from this? As an example, if a number appears an odd number of times, the last appearance of it should be kept. All others should be removed. Including all the ones that appear an even number of times.
ex: From '9♡', '9♢', '9♣', only the '9♣' should be kept.
Can someone help me with this?
I tried to use the below code to identify indices first. But still no luck.
i = 0
while i < len(deck):
count = 0
k = len(deck[i])
pivot = i
j = i
while j < len(deck):
if deck[i][:k-1] == deck[j][:k-1]:
print(deck[i]+','+deck[j])
count+= 1
pivot = j
j+=1
if (count %2 != 0):
print('pivot:'+str(pivot))
i = pivot +1
i +=1
No need to consider symbols. Just want to remove pairs from the list.
Please provide your suggestions.
Is this what you are looking for?
from collections import defaultdict
deck = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
# Create a dictionary and group all the cards with same number
groups = defaultdict(list)
for card in deck:
key = card[:-1]
groups[key].append(card)
new_deck = []
for subgroup in groups.values():
# iterate through the dictionary
# If you have odd number of cards in a subgroup
# consider the last card in that subgroup
if len(subgroup)%2 == 1:
new_deck.append(subgroup[-1])
for card in new_deck:
print(card)
Output
2♡ 8♣ 9♣ A♣ J♢ Q♡
Edit: A minor simplification to the second iteration with groups.values, thanks to RoadRunner.
Group the card pairs into a collections.defaultdict, then only return the last card from uneven pairs in a new list using a list comprehension:
from collections import defaultdict
lst = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
cards = defaultdict(list)
for card in lst:
cards[card[:-1]].append(card)
result = [pairs[-1] for pairs in cards.values() if len(pairs) % 2]
print(result)
Output:
['2♡', '8♣', '9♣', 'A♣', 'J♢', 'Q♡']
Keeping the same order, you can use:
import re
l = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
nc, nl = [], [0]
for x in l:
clean = re.sub(r"[^A-Z\d]", "", x)
if clean != nl[-1]:
nl.append(clean)
nc.append(x)
else:
del nl[-1]
del nc[-1]
print(nc)
# ['2♡', '8♣', '9♣', 'A♣', 'J♢', 'Q♡']
Demo
First of all, list is a reserved keyword, you should never name your variables after reserved keywords, use lst instead of list
Now, Here is the minimal solution:
lst = ['10♠', '10♣', '2♡', '4♠', '4♣', '5♡', '5♣', '6♡', '6♣', '7♠', '7♡', '7♢', '7♣', '8♡', '8♢', '8♣', '9♡', '9♢', '9♣', 'A♠', 'A♢', 'A♣', 'J♢', 'K♠', 'K♢', 'Q♡']
dictionary = dict.fromkeys(list('A23456789JQK')+['10'])
for item in lst:
dictionary[item[:-1]] = item if dictionary[item[:-1]] is None else None
print(list(filter(None.__ne__, dictionary.values())))
output:
['A♣', '2♡', '8♣', '9♣', 'J♢', 'Q♡']
I have dictionary, which contains different list.
I want toc combine data in different dictionary appending values of similar keys in it.
{'mental_issue': ['stress', 'live in fear', 'stomach curl', 'wracked by stress', 'chest tighten']}
{'sexual_abuse': ['stalking'], 'mental_issue': ['abuse', 'pica']}
{}
{'verbal_abuse': ['in the face'], 'mental_issue': ['abuse']}
{}
{'mental_issue': ['abuse']}
{'mental_issue': ['abuse']}
{'mental_abuse': ['name call'], 'mental_issue': ['abuse']}
{}
{'mental_issue': ['broken jaw', 'abuse', 'heart broken']}
{'mental_issue': ['live in fear']}
{'mental_issue': ['abuse', 'trauma']}
{'mental_issue': ['nightmares', 'abuse', 'panic attack']}
{'mental_issue': ['stress']}
{'mental_issue': ['severe']}
{'mental_issue': ['nightmares', 'bad emotional state']}
{'sexual_abuse': ['rape'], 'mental_issue': ['stress', 'paranoia']}
{'mental_issue': ['fracturing both my', 'both my knees']}
{'mental_issue': ['abuse']}
{'sexual_abuse': ['rape'], 'verbal_abuse': ['kicking'], 'mental_issue': ['nightmares']}
I want to combine values of all issues like mental_abuse should have all mental aboses from all dictionary.
I wrote this logic -
sexual_abuse_list = []
d = {'sexual_abuse': ['rape'], 'verbal_abuse': ['kicking'], 'mental_issue': ['nightmares']}
if 'sexual_abuse' in d:
for item in d['sexual_abuse']:
sexual_abuse_list.append(item)
Is this correct logic? or any better logic can be written?
Using collections.defaultdict
Ex:
from collections import defaultdict
lst = [{'mental_issue': ['stress', 'live in fear', 'stomach curl', 'wracked by stress', 'chest tighten']},
{'sexual_abuse': ['stalking'], 'mental_issue': ['abuse', 'pica']},
{},
{'verbal_abuse': ['in the face'], 'mental_issue': ['abuse']},
{},
{'mental_issue': ['abuse']},
{'mental_issue': ['abuse']},
{'mental_abuse': ['name call'], 'mental_issue': ['abuse']},
{},
{'mental_issue': ['broken jaw', 'abuse', 'heart broken']},
{'mental_issue': ['live in fear']},
{'mental_issue': ['abuse', 'trauma']},
{'mental_issue': ['nightmares', 'abuse', 'panic attack']},
{'mental_issue': ['stress']},
{'mental_issue': ['severe']},
{'mental_issue': ['nightmares', 'bad emotional state']},
{'sexual_abuse': ['rape'], 'mental_issue': ['stress', 'paranoia']},
{'mental_issue': ['fracturing both my', 'both my knees']},
{'mental_issue': ['abuse']},
{'sexual_abuse': ['rape'], 'verbal_abuse': ['kicking'], 'mental_issue': ['nightmares']}]
d = defaultdict(list)
for i in lst:
for k, v in i.items():
d[k].extend(v)
print(d)
Output:
defaultdict(<type 'list'>, {'sexual_abuse': ['stalking', 'rape', 'rape'], 'verbal_abuse': ['in the face', 'kicking'], 'mental_abuse': ['name call'], 'mental_issue': ['stress', 'live in fear', 'stomach curl', 'wracked by stress', 'chest tighten', 'abuse', 'pica', 'abuse', 'abuse', 'abuse', 'abuse', 'broken jaw', 'abuse', 'heart broken', 'live in fear', 'abuse', 'trauma', 'nightmares', 'abuse', 'panic attack', 'stress', 'severe', 'nightmares', 'bad emotional state', 'stress', 'paranoia', 'fracturing both my', 'both my knees', 'abuse', 'nightmares']})
How can I get a random pair from a dict? I'm making a game on black jack so user will get a random pair from
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
and it will get stored in a dictionary
player_deck = {}
How can I do this?
Use random.choice()
import random
player_deck = {}
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
key, value = random.choice(list(deck_of_cards.items()))
player_deck[key] = value
Or in case you want key and value directly into a dictionary, you can do it like this
player_deck = dict([random.choice(list(deck_of_cards.items()))])
It's not really clear how you want to simulate a deck with this dict.
If you just use random.choice multiple times, you might get the same card twice, which probably shouldn't happen.
You could create a whole deck (as a list, not as a dict), shuffle it, draw a card (thus removing it from the deck), and check its value.
Defining a new Card class isn't too hard with namedtuple, and it will make it easier to work with afterwards (Thanks to #MaartenFabré for the comment):
# encoding: utf-8
import random
from collections import namedtuple
class Card(namedtuple('Card', ['face', 'color'])):
colors = ['♠', '♥', '♦', '♣']
faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
values = dict(zip(faces, [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]))
def __repr__(self):
return self.face + self.color
def value(self):
return Card.values[self.face]
#staticmethod
def all():
return [Card(face, color)
for color in Card.colors for face in Card.faces]
deck = Card.all()
print(deck)
# ['A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠', 'A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣']
random.shuffle(deck)
print(deck)
# ['9♣', '4♠', 'J♥', '9♦', '10♠', 'K♣', '8♥', '3♣', 'J♣', '10♦', '8♦', 'A♣', '7♦', '3♠', '7♠', 'Q♣', '7♥', 'Q♦', 'A♦', '9♥', '2♠', '7♣', '6♦', '4♣', 'Q♠', '3♥', 'K♠', '6♣', '5♦', '4♥', '5♣', '2♣', '2♥', '6♥', '8♠', '2♦', '4♦', '8♣', 'K♦', '10♥', 'K♥', '5♠', 'J♦', '5♥', 'A♥', '9♠', '6♠', 'Q♥', '10♣', 'A♠', '3♦', 'J♠']
a_card = deck.pop()
print(a_card)
# J♠
print(a_card.face)
# J
print(a_card.color)
# ♠
print(a_card.value())
# 10
Use random.choice
import random
player_deck = {}
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
d = random.choice(list(deck_of_cards.items()))
player_deck.update(d)
print(player_deck)
{'9': 9}
You can do something like this:
import random
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
player_deck = dict(random.sample(deck_of_cards.items(),1))
where I am basically asking for '1' random sample from the dictionary and typecasting the output to a dictionary (as it returns a list).
You can use random.choice:
import random
player_deck=[]
player_deck.append(random.choice(list(deck_of_cards.items())))
print(player_deck)